我是Angular 2的新手,我正在玩环境来创建一些应用程序。做网站Angular.io之类的事情说我能够创建一个可注入服务并在我的AppComponent上使用它,但仅限于如果我从同一个.ts文件中读取数据,如this.sourceData = {...}。如果我从Rest服务获取json数据,则数据未定义
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
{
"classroom": {
"Id": "01",
"totalStudents": "2",
"Students": [{
"Name": "Jhon",
"age": "18"
}, {
"Name": "Doe",
"age": "18"
}],
"Teachers": [{
"Name": "Jane",
"age": "38"
}, {
"Name": "Doe",
"age": "35"
}]
}
}
使用Observables时我错过了什么? 提前致谢
答案 0 :(得分:1)
当你调用response.json()时,它会自动从ajax响应中获取data属性并返回它,所以在extractData方法中删除你对.data的引用。
getData() : Observable<any> {
return this.http.get(this.dataUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
return res.json();
//return body.data || {}; // <-- this line needs to go
}
仅供参考,因为您的extractData方法减少到一行,大多数示例(和现实生活)代码只会在地图函数中内联调用
getData() : Observable<any> {
return this.http.get(this.dataUrl)
.map(response => response.json())
.catch(this.handleError);
}