Home > Mobile >  Rxjs subscribe deprication
Rxjs subscribe deprication

Time:06-12

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;
}

CodePudding user response:

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.

this.bookService.getBooks().subscribe({
  next: (value) => {
    this.books=value;
    console.info("Next: " value.text); //console shows value is undefined
  },
  error: (value) => {
    alert(value.message);
  },
  complete: () => {
    console.info('complete');
  }
});
  • Related