【发布时间】:2017-03-28 02:03:36
【问题描述】:
我是 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 时是否遗漏了什么? 提前致谢
【问题讨论】:
-
控制台有什么错误吗?
-
打开你的控制台,也许你可以在这里看到关于“CORS”的错误。
-
这不是 CORS 问题,我已经修复了它。控制台上的第一个错误是:错误类型错误:无法读取 Object.eval [as updateRenderer] (ng:///AppModule/AppComponent.ngfactory.js:25:34) at Object.debugUpdateRenderer [作为 updateRenderer] (localhost:4200/vendor.bundle.js:13612:21)
-
您可以尝试使用安全导航运算符吗?像这样:
<p> {{ theData?. classroom?.Id }}</p>