Subscribe is deprecated: Use an observer instead of an error callback
Asked Answered
D

10

338

When I run the linter it says:

subscribe is deprecated: Use an observer instead of an error callback

Code from this angular app:

    this.userService.updateUser(data).pipe(
       tap(() => {bla bla bla})
    ).subscribe(
       this.handleUpdateResponse.bind(this),
       this.handleError.bind(this)
    );

Don't know exactly what should I use and how...

Thanks!

Discretional answered 2/4, 2019 at 10:8 Comment(3)
* so try using .subscribe({ next: this.handleUpdateResponse.bind(this), error: this.handleError.bind(this) })Isentropic
I don't manage to make it work using my apiRestGrecian
A detailed answer could be found here jeffryhouser.com/index.cfm/2019/8/27/…Celiotomy
M
483

subscribe isn't deprecated, only the variant you're using is deprecated. In the future, subscribe will only take one argument: either the next handler (a function) or an observer object.

So in your case you should use:

.subscribe({
   next: this.handleUpdateResponse.bind(this),
   error: this.handleError.bind(this)
});

See these GitHub issues:

Musaceous answered 2/4, 2019 at 10:19 Comment(9)
idk... hovering in vs code still shows deprecated with that syntax (rxjs 6.5.3)Surveying
Hey @YannicHamann this comment explains why. It's not deprecated, they just deprecated one of the overloads and now it looks like everything is deprecated. It's a tooling issue mostly.Mien
I think this answer is not anymore valid since all subscribe methods are deprecated now in rxjs 6.5.4Wisteria
It there a migration script that will automatically update all our subscribe() methods? We have hundreds of them in our project, I can't imagine having to do this manually!Truda
@AlokRajasukumaran how are we suposed subscribe nowadays?Patisserie
We actually went to a normal method without rxjs for the same.Wisteria
@AlokRajasukumaran Not all methods are deprecated now. It's just that certain tools misinterpret the source and think all are deprecated. (see: Code on github)Reface
Hmm, weird. The deprecated warning does not disappear after fix.Armil
I'm using the preferred syntax in all my components and still getting the deprecation message.Flit
K
171

Maybe interesting to note that the observer Object can also (still) contain the complete() method and other, additional properties. Example:

.subscribe({
    complete: () => { ... }, // completeHandler
    error: () => { ... },    // errorHandler 
    next: () => { ... },     // nextHandler
    someOtherProperty: 42
});

This way it is much easier to omit certain methods. With the old signature it was necessary to supply undefined and stick to the order of arguments. Now it's much clearer when for instance only supplying a next and complete handler.

Kersey answered 11/7, 2019 at 9:19 Comment(3)
How to access real this, if using this form?Allhallows
Not sure what you mean with real this. It's always possible to use a variable, something like let scopedThis = this or you can you bind() for instance.Kersey
Exactly what I was looking for! When passing an observer object into subscribe() there is no need to explicitly type undefined as a missing argument when you don't want to specify next() or error() callbacks.Jena
D
55

For me, it was just the typescript version my VSCode was pointing to.

VSCode status bar

TypeScript version selector

Select local TypeScript version

Got help from this GitHub comment.

I believe this is a typescript issue. Something in the newest versions of typescript is causing this warning to display in vs code. I was able to get it to go away by click the version of typescript in the bottom right corner of vs code and then choosing the select typescript version option. I set it to the node_modules version we have installed in our angular project which in our case happens to be 4.0.7. This caused the warnings to go away.

Duologue answered 18/3, 2021 at 13:7 Comment(0)
G
34

Find the details at official website https://rxjs.dev/deprecations/subscribe-arguments

Notice the {} braces in second subscribe code below.

import { of } from 'rxjs';

// recommended 
of([1,2,3]).subscribe((v) => console.info(v));
// also recommended
of([1,2,3]).subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete') 
})
Gnaw answered 13/2, 2022 at 9:13 Comment(0)
M
23

You can get this error if you have an object typed as Observable<T> | Observable<T2> - as opposed to Observable<T|T2>.

For example:

    const obs = (new Date().getTime() % 2 == 0) ? of(123) : of('ABC');

The compiler does not make obs of type Observable<number | string>.

It may surprise you that the following will give you the error Use an observer instead of a complete callback and Expected 2-3 arguments, but got 1.

obs.subscribe(value => {

});

It's because it can be one of two different types and the compiler isn't smart enough to reconcile them.

You need to change your code to return Observable<number | string> instead of Observable<number> | Observable<string>. The subtleties of this will vary depending upon what you're doing.

Mcreynolds answered 11/7, 2019 at 4:35 Comment(1)
This worked for me, deleteNoteType( NoteTypeId: number ): Observable<HttpResponse<undefined> | HttpErrorResponse> { ... }Phylis
S
22

The new Way of using RxJS is quit simple:

previous versions:

this.activatedRoute.queryParams.subscribe(queryParams => {
console.log("queryParams, queryParams)

}, error => {
})

New Version:

  this.activatedRoute.queryParams.subscribe(
  {
    next: (queryParams) => {
      console.log('queryParams', queryParams);
    },

    error: (err: any) => { },
    complete: () => { }
  }
);
Sperry answered 14/11, 2022 at 7:36 Comment(0)
A
4

I migrated my Angular project from TSLint to ESLint and it is now not showing the warning anymore!

I followed these steps. (End of each step I also recommend to commit the changes)

  1. Add eslint: ng add @angular-eslint/schematics

  2. Convert tslint to eslint: ng g @angular-eslint/schematics:convert-tslint-to-eslint

  3. Remove tslint and codelyzer: npm uninstall -S tslint codelyzer

  4. If you like to auto fix many of the Lint issues ng lint --fix (It will also list the not fixed issues)

  5. In VSCode uninstall the TSLint plugin, install ESLint plugin and Reload the VSCode.

  6. Make sure it updated the package and package-lock files. Also the node_modules in your project.

  7. If you have the tsconfig.json files under sub directory - you need to add/update the projects-root-directory/.vscode/settings.json with the sub directory where the tsconfig files are!

    {
      "eslint.workingDirectories": [
        "sub-directory-where-tsconfig-files-are"
      ]
    }
    
Amputee answered 5/5, 2021 at 21:25 Comment(1)
More details here, about migration from TSLint to ESNint, in VS Code official page: code.visualstudio.com/api/advanced-topics/…Mundane
P
2

I was getting the warning because I was passing this to subscribe:

myObs.subscribe(() => someFunction());

Since it returns a single value, it was incompatible with subscribe's function signature.

Switching to this made the warning go away (returns null/void);

myObs.subscribe(() => {
  someFunction();
});
Potion answered 22/5, 2020 at 17:15 Comment(0)
Z
2

The new syntax of subscribe :

 this.fetch().subscribe({
        next: (account: Account) => {
            console.log(account);
            console.log("Your code ...");
        },

        error: (e) => {
            console.error(e);
        },

        complete() {
          console.log("is completed");
        },
});
Zebadiah answered 30/8, 2023 at 10:6 Comment(1)
What's the purpose of the complete callback? Is it somewhat similar to promise finally ?Benoni
P
1

You should replace tslint with eslint.

As TSLint is being deprecated it does not support the @deprecated syntax of RXJS. ESLint is the correct linter to use, to do subscribe linting correctly.

Pisces answered 4/4, 2021 at 13:15 Comment(3)
I don't think this solution is good, because ignoring a problem doesn't solve it.Ganister
In this case it's not a matter of ignoring the problem because seems to be only a TSLint bug: https://mcmap.net/q/100423/-angular-11-subscribe-is-deprecated-use-an-observer-instead ... but more important to know is that TSLint has been deprecated in favour of ESLint: https://mcmap.net/q/100423/-angular-11-subscribe-is-deprecated-use-an-observer-insteadVinna
It's not ignoring, it removes a false error.Jarrett

© 2022 - 2024 — McMap. All rights reserved.