[英]How to get data from external api?
我是Angular2的新手。 我要编写单页应用程序,我需要从后端获取json的可能性。
我在网上找到了很多示例,但没有人适合我...:/我花了2天的时间尝试运行和调试...
我写了这段代码:
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/Rx';
export class Comp {
id:number;
name:string;
cmd:string;
builds:[Build]
}
export class Build {
id:number;
name:string;
status:string;
component_id:number;
}
@Component({
selector: 'my-app',
template: `
<h1>MYAPP</h1>
<ul>
<li *ngFor="#comp of comps">
<b>{{ comp.name }} <=> {{ comp.cmd }}</b>
<ul>
<li *ngFor="#build of comp.builds">
<b>{{ build.name }} <=> {{ build.id }}</b>
</li>
</ul>
</li>
</ul>
`
})
export class AppComponent {
constructor(private http: Http) {}
public comps;
ngOnInit() {
this.getComps();
}
getComps() {
return this.http.get('http://localhost:4000/components')
.map((res:Response) => res.json())
.subscribe(
data => { this.comps = data},
err => console.error(err),
() => console.log(this.comps)
);
}
}
我想从网络获取Comp模型并使用@template进行显示。 我试图在Google Chrome控制台中调试它,并且this.comps变量未定义。 应用程序从后端获取json,但我不知道为什么要使用它并将其存储在变量中。 我想我的代码中有一个小错误,但是我不知道在哪里。 :(
有谁能够帮助我?
验证res.json()
在.map((res:Response) => res.json())
包含您认为它的数据。
我建议如下创建一个辅助方法并设置一个断点:
getComps() {
return this.http.get('http://localhost:4000/components')
.map(this.extractData)
.subscribe(
data => { this.comps = data},
err => console.error(err),
() => console.log(this.comps)
);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
//set breakpoint here and value of body.
let body = res.json();
//some web servers package the API call return value in a .data object.
//others do not. So, we check to check...
if (body) {
if (body.data) {
return body.data;
}
else {
return body;
}
}
else {
return [];
}
}
我遇到了同样的问题,结果表明IIS Express 并未将返回值包装在.data
对象中,并且if(body){...}
没有上述if(body){...}
检查代码,则ngFor
会阻塞空的{}
宾语。
它应该工作:)
@Component({
selector: 'my-app',
template: `
<h1>MYAPP</h1>
<ul>
<li *ngFor="#comp of comps">
<b>{{ comp?.name }} <=> {{ comp?.cmd }}</b>
<ul>
<li *ngFor="#build of comp.builds">
<b>{{ build?.name }} <=> {{ build?.id }}</b>
</li>
</ul>
</li>
</ul>
`
干杯
如果您的JSON数据是Comp对象的数组,则必须执行以下两个步骤:
export class Comp { id:number; name:string; cmd:string; builds:Build[];//this was your first fault }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.