user963241
user963241

Reputation: 7048

Why 'next' is omitted from subscribe call in observable?

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?

Upvotes: 0

Views: 74

Answers (1)

Meqwz
Meqwz

Reputation: 1491

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) => {}
    );

Upvotes: 1

Related Questions