I’m new in Angular 2 and I’m playing with the environment to create some app. Doing the things like the site Angular.io says I’m able to create an Injectable Service and using it on my AppComponent but only If I read the data from the same .ts file like this.sourceData = {…}. If I get the json data from a Rest service the data is undefined
app.service.ts
Import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class WebService {
private dataUrl = 'http://localhost:8080/api/home';
constructor(private http: Http) { }
getData() : Observable<any> {
return this.http.get(this.dataUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { WebService } from './app.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [WebService]
})
export class AppComponent implements OnInit {
errorMessage: string;
theData: Object;
constructor(private dataService: WebService) {}
ngOnInit() { this.getDataFromService(); }
getDataFromService() {
this. dataService. getData ()
.subscribe(
myData => this.theData = myData,
error => this.errorMessage = <any>error);
}
}
app.component.html
<p> {{ theData. classroom.Id }}</p>
JSON from service
{
"classroom": {
"Id": "01",
"totalStudents": "2",
"Students": [{
"Name": "Jhon",
"age": "18"
}, {
"Name": "Doe",
"age": "18"
}],
"Teachers": [{
"Name": "Jane",
"age": "38"
}, {
"Name": "Doe",
"age": "35"
}]
}
}
Am I missing something when using Observables? Thanks in advance
{{ theData?. classroom?.Id }}
` – eko Mar 28 '17 at 05:28