Reputation: 421
I am attempting to create an Observable from an HTTP Get request in my app.services.ts file and have it move data between my two controllers.
I have the variable that I want defined in my controller and I have injected the service to the controller's constructor without any errors, but when I log the variable to the console when my app loads I get undefined
.
app.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
constructor(private _http: Http) { }
getContacts() {
return this._http.get('assets/api/contacts.json')
.map((response: Response) => response.json());
}
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
contacts: any[]; <-- //this is where I defined my variable
errorMessage: string;
constructor (private _apiService: ApiService) {}
ngOnInit(){ this.getContacts();
console.log(this.contacts); <-- //This is where I get undefined
}
getContacts() {
this._apiService.getContacts()
.subscribe(contacts => this.contacts = contacts,
error => this.errorMessage = error);
}
}
Upvotes: 1
Views: 40
Reputation: 31915
You got undefined because of contacts
was declared but not initialized and the service is async, it's not ready when you print it out.You can add
getContacts() {
this._apiService.getContacts()
.subscribe(
(contacts) => {
this.contacts = contacts;
console.log(this.contacts); // add it here
},
(error) => {
this.errorMessage = error;
}
}
Upvotes: 1