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

痴心易碎 提交于 2019-11-27 12:43:39

问题


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!


回答1:


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:

  • https://github.com/ReactiveX/rxjs/pull/4202

  • https://github.com/ReactiveX/rxjs/issues/4159




回答2:


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.




回答3:


You can get this error if you have an object that can represent two different types Observable<T> | Observable<T2>.

For example:

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

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.



来源:https://stackoverflow.com/questions/55472124/subscribe-is-deprecated-use-an-observer-instead-of-an-error-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!