我在Angular 7中具有以下服务方法:
TreeView
在组件上,我有:
public getTopPosts(): Observable<Payload<PostResponse>> {
return this.httpClient.get<Payload<PostResponse>>('/top-posts');
}
HTML组件是:
export class TopPostsComponent implements OnInit {
posts: PostModel[] = [];
constructor(private postService: PostService) { }
ngOnInit() {
this.getPosts();
}
getPosts() {
this.postService.getTopPosts().subscribe((payload: Payload<PostResponse>) => {
this.posts = payload.map((response: PostResponse) => {
return {
id: response.id,
title: response.title
};
});
});
}
}
它正在工作,但是我想在加载数据时显示“正在加载”。
是否可以在组件上不使用额外的变量?
答案 0 :(得分:2)
不确定如何将其标记为重复项,因此我在Angular 4 async with loading and display when empty处发布了指向类似问题的链接作为答案。
您将不得不更新您的可观察对象以使用异步管道,因此它将是这样的:
export class TopPostsComponent implements OnInit {
posts$: Observable<PostModel[]>;
constructor(private postService: PostService) { }
ngOnInit() {
this.getPosts();
this.posts$ = this.postService.getTopPosts().pipe(
map((payload: Payload<PostResponse>) => {
return payload.map((response: PostResponse) => { id: response.id, title: response.title});
})
);
}
}
<div *ngIf="(posts$ | async)?.length > 0; else loading">
<ng-container *ngFor="let post of posts$ | async">
<div>{{post.title}}</div>
<ng-container>
</div>
<ng-template #loading>loading posts...</ng-template>
答案 1 :(得分:0)
您无法初始化posts: PostModel[]
并使用<div *ngIf="!posts" >loading...</div>
。就像Osakr在评论中指出的那样:将this.posts
设置为[]
,因为否则,如果调用失败,它将继续加载。
您的新代码如下:
export class TopPostsComponent implements OnInit {
posts: PostModel[];
constructor(private postService: PostService) { }
ngOnInit() {
this.getPosts();
}
getPosts() {
this.postService.getTopPosts().subscribe((payload: Payload<PostResponse>) => {
this.posts = payload.map((response: PostResponse) => {
return {
id: response.id,
title: response.title
};
},
error => { this.posts = [] }
);
});
}
}
HTML是:
<div *ngIf="!posts">
loading...
</div>
<div *ngFor="let post of posts">
{{post.title}}
</div>