'Angular 11: subscribe is deprecated: Use an observer instead?

My tslint gone crazy? It gives warning for every subscribtion I made in whole app. It doesn't matter if I use old or new syntax it still says that subscribe is deprecated... How to write a subscription that will not be deprecated?

That's what was ok till today:

something.subscribe((user: User) => {
        this.userProviderService.setUserId(user.userId);
        this.proceed = true;
      });

I tried new syntax but makes no change:

something.subscribe({
        next: (user: User) =>  {
          this.userProviderService.setUserId(user.userId);
          this.proceed = true;
        },
        complete: () => {},
        error: () => {}
      });

This is exactly what it's saying:

(method) Observable.subscribe(next?: (value: Object) => void, error?: (error: any) => void, complete?: () => void): Subscription (+4 overloads) @deprecated — Use an observer instead of a complete callback

@deprecated — Use an observer instead of an error callback

@deprecated — Use an observer instead of a complete callback

subscribe is deprecated: Use an observer instead of a complete callback (deprecation)tslint(1)

So how do I subscribe to things now?



Solution 1:[1]

I just looked up TSLint (v1.3.3) at VS Code extenstions tab. It says:

?IMPORTANT: TSLint has been deprecated in favor of ESLint.

As I disabled TSLint and installed ESLint, all warnings related to subscribtions dissapeared.

Cheers!

Solution 2:[2]

To answer your question "So how do I subscribe to things now": https://rxjs-dev.firebaseapp.com/guide/observer This is it. It is easy to use and pretty similar to what has been done before with the small change that it actually now accepts an object (observer) with 3 keys: next, error, complete.

We had the same discussion like 2 days ago at work and altough you can/should use the observer the deprecation seems to be a false alarm. (We thought we had to change ~900 subscribes):

This is an issue created on the rxjs github page regarding this issue: https://github.com/ReactiveX/rxjs/issues/6060

And in it the devs say it is due to a typescript bug: https://github.com/microsoft/TypeScript/issues/43053

This bug already has been fixed 3 days ago, i am not sure though if it is already in the newest release:

https://github.com/microsoft/TypeScript/pull/43165

Solution 3:[3]

Better way to solve it

I had the same problem and I solved it by using in that way which is more clear.

myObservable.subscribe({
    next: (val) => { ... },
    error: (err) => { ... },
    complete: () => { ... }     
});

I was experiencing this in Angular v13 and solved it by using above code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smokovsky
Solution 2 Fabian Schmidt
Solution 3