Mig*_*ura 8 typescript angular angular6 angular7
我正在订阅来自 Angular 服务的响应:
books: BookModel[] = [];
constructor(private bookService: BookService) { }
ngOnInit() {
this.books = this.getBooks();
}
getBooks(): BookModel[] {
return this.bookService.getByCategoryId(1).subscribe((payload: Payload<GetBooksResponse>) => {
return payload.result.map((response: GetBooksResponse) => {
return {
id: response.id,
title: response.title
};
});
});
}
Run Code Online (Sandbox Code Playgroud)
当我添加return到时this.bookService,例如,return this.bookService我收到错误:
Type 'Subscription' is missing the following properties from type 'BookModel[]': length, pop, push, concat, and 26 more.
Run Code Online (Sandbox Code Playgroud)
我如何使用 return 来完成这项工作?
更新:书模型:
export interface BookModel {
id: number;
title: string;
}
Run Code Online (Sandbox Code Playgroud)
您正在尝试将订阅分配到一个数组中,这就是您收到这些错误的原因:
我使用 Observables 和异步管道制作了这个示例,希望对您有所帮助:
TS:
/***
* books$ Observable is looking to any response
* of the method getByCategoryId. It is being displayed with async pipe in the view.
*/
books$ = this.bookService.getByCategoryId(1);
books: BookModel[];
constructor(private bookService: BookService) { }
ngOnInit() {
this.getBooks();
}
/***
* Getbooks method does not return anything,
* after the subscribe, a map is assigning the value to the books propertie
* which is in being render in the view without async pipe.
*/
getBooks(): void {
this.bookService.getByCategoryId(1)
.subscribe((payload: Payload<GetBooksResponse>) => {
this.books = payload.result.map((response: GetBooksResponse) => {
return <BookModel>{
id: response.id,
title: response.title
};
});
});
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div *ngFor="let book of (books$ | async).result">
{{ book | json }}
</div>
<br/>
<h3> Not Using | async </h3>
<div *ngFor="let book of books">
{{ book | json }}
</div>
Run Code Online (Sandbox Code Playgroud)
在此链接在线尝试:https : //stackblitz.com/edit/angular-k9pzmw
如果你问我哪种方法更好,我会说这取决于。
带有 observable 的异步管道是我最喜欢只在视图中显示“哑数据”的,但是如果您需要在组件中使用此信息以用于其他任何事情,您应该保留订阅解决方案。
| 归档时间: |
|
| 查看次数: |
33268 次 |
| 最近记录: |