When I run the linter it says:
subscribe is deprecated: Use an observer instead of an error callback
Code (from an angular 7 app with angular-cli):
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!
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:
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.
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.