后期服务文件
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Injectable} from "angular2/core";
@Injectable()
export class PostService {
private url = "http://jsonplaceholder.typicode.com/posts";
constructor(private _http: Http) {
}
getData() {
return this._http.get(this.url)
.map(res => res.json());
}
}
<小时/>
app.component.ts
应用程序组件使用帖子服务(上面)来检索一些数据,我想在页面中呈现。
import {Component} from 'angular2/core';
import { Observable } from 'rxjs/Rx';
///<reference path="../typings/jquery/jquery.d.ts" />
import {PostService} from './post.service';
import {HTTP_PROVIDERS} from 'angular2/http';
@Component({
selector: 'my-app',
template:`
<ul>
<li *ngFor="#item of items"> {{item.title}} </li>
</ul>
`,
providers:[PostService, HTTP_PROVIDERS]
})
export class AppComponent {
items = [];
constructor(private postService: PostService){
this.postService.getData()
.subscribe(function (data) {
this.items = data;
});
}
}
它没有给出任何错误,但也没有渲染,有人可以帮忙吗?
提前致谢。
最佳答案
我看到的一个问题是:
<li *ngFor="#item of items">
假设您使用的是 rc.1 版本(截至 2016 年 5 月 11 日的最新版本),正确的语法是:
<li *ngFor="let item of items">
此外,这可能不是问题,但您的“订阅”代码块与我通常的代码块有点不同。
你的:
this.postService.getData()
.subscribe(function (data) {
this.items = data;
});
我会怎么做:
this.postService.getData()
.subscribe(
data => this.items = data,
error => alert(error),
() => console.log("Subscribed")
)};
希望这有帮助!
关于javascript - ngFor指令模板渲染ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37173435/