RXJS订阅编写
经过教程后,我注意到“订阅”正在弃用。我尝试关注 https://rxjs.dev/deprecations/subscribe-arguments-subscribe-arguments 如< typescript折旧警告,但无法更新到新方法。
我包括有关代码。任何帮助指出我出错的位置,以将弃用的方法移植到新方法的位置。
public books: Book[] | undefined;
constructor(private bookService: BookService) {}
ngOnInit() { this.getBooks(); }
public getBooks(): void{
// Reference: https://rxjs.dev/deprecations/subscribe-arguments
// **deprecated:** This work, and I can see this.books has values
// this.bookService.getBooks().subscribe(
// (response: Book[])=>{this.books=response},
// (error: HttpErrorResponse)=> {alert(error.message);}
// );
// **New approach** This compiles but value is undefined.
of([this.bookService.getBooks()]).subscribe({
next: (value:any) => {
this.books=value;
console.info("Next: "+value.text); //console shows value is undefined
},
error: (value) => {
alert(value.message);
},
complete: () => {
console.info('complete');
}
}
);
export interface Book{
title: string;
author: string;
}
After going through a tutorial, I noticed the 'subscribe' was being deprecated. I tried following https://rxjs.dev/deprecations/subscribe-arguments and some stackoverflow questions like Typescript Deprecation warning but was not able to update to the new approach.
I've include the code in question. Any help pointing out where I went wrong porting the deprecated approach to the new approach would be appreciated.
public books: Book[] | undefined;
constructor(private bookService: BookService) {}
ngOnInit() { this.getBooks(); }
public getBooks(): void{
// Reference: https://rxjs.dev/deprecations/subscribe-arguments
// **deprecated:** This work, and I can see this.books has values
// this.bookService.getBooks().subscribe(
// (response: Book[])=>{this.books=response},
// (error: HttpErrorResponse)=> {alert(error.message);}
// );
// **New approach** This compiles but value is undefined.
of([this.bookService.getBooks()]).subscribe({
next: (value:any) => {
this.books=value;
console.info("Next: "+value.text); //console shows value is undefined
},
error: (value) => {
alert(value.message);
},
complete: () => {
console.info('complete');
}
}
);
export interface Book{
title: string;
author: string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想此处的错误是您包装
this.bookService.getBooks()
在数组中。如果您卸下方括号,则应工作。另外,您无需在此处使用()的
。只需订阅正常即可。
I suppose the error here is that you wrapped
this.bookService.getBooks()
inside an array. If you remove the square brackets it should work.Also you don't need to use
of()
here. Just subscribe as normal.