0
我是Angular 2中的新成员,我正在使用环境来创建一些应用程序。做网站Angular.io这样的事情说我能够创建一个Injectable Service,并在我的AppComponent上使用它,但是只有当我从像.sourceData = {...}这样的.ts文件读取数据时。如果我从一个REST服务获取JSON数据的数据不确定Angular 2无法从Rest服务获取数据
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问题,我已经修复它。控制台上的第一个错误是:ERROR TypeError:无法读取对象的Object.eval [as updateRenderer](ng:///AppModule/AppComponent.ngfactory.js:25:34) 上未定义的 的属性'教室'。 debugUpdateRenderer [as updateRenderer](http:// localhost:4200/vendor.bundle.js:13612:21) –