@Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private http: HttpClient) { }
getPosts(): Observable<Array<any>> {
return this.http.get<Array<any>>(`http://localhost:9000/posts`);
}
}
根据Angular docs,我可以通过两种方式使用“*ngFor”在我的组件中显示此集合:
或:
@Component({
selector: 'app-root',
template: '<div *ngFor="let post of posts">{{post.title}}</div>'
})
export class AppComponent {
posts: any[];
constructor(public postService: PostService) {}
ngOnInit() {
this.postService.getPosts().subscribe(_posts => this.posts= _posts);
}
}
@Component({
selector: 'app-root',
template: '<div *ngFor="let post of posts$ | async">{{post.title}}</div>'
})
export class AppComponent {
posts$: Observable<Array<any>>;
constructor(public postService: PostService) {}
ngOnInit() {
this.posts$ = this.postService.getPosts()
}
}
我的问题是:为什么这样写是错误的?(很明显,所有“ngOnInit东西”都可以幸免):
@Component({
selector: 'app-root',
template: '<div *ngFor="let post of postService.getPosts() | async">{{post.title}}</div>'
})
export class AppComponent {
posts$: Observable<Array<any>>;
constructor(public postService: PostService) {}
}
我可以看出这是发送无尽的请求到服务器,但为什么?
谢谢