Home > Back-end >  Why 'next' is omitted from subscribe call in observable?
Why 'next' is omitted from subscribe call in observable?

Time:01-23

I am trying to understand the following line:

this.userService.save(this.user).subscribe(result => this.gotoUserList());

This appear to work, but what about next:? When I try to include it e.g.

this.userService.save(this.user).subscribe(next: result => this.gotoUserList());

Then I get an error 'name not found'. What's going on here?

CodePudding user response:

I believe this is the syntax you want:

this.userService.save(this.user).subscribe({ next: () => this.gotoUserList() });

The using all three observable methods would look like this:

this.userService.save(this.user).subscribe({
      next: () => {
        this.gotoUserList();
      },
      error: () => {
        // do something
      },
      complete: () => {
        // do something
      },
  })

I have never seen next used in a subscriber in Angular. It's valid syntax, but practically, no code I've ever encountered does this. In the first example, you use the shorthand version, which assumes that you want to do some action on the next observable emission.

The shorthand version is this:

.subscribe(() => {
      this.gotoUserList();
    },
    (err) => {},
    (complete) => {}
    );
  • Related