当我运行它时,它说:
subscribe is deprecated: Use an observer instead of an error callback
代码(来自角度为cli的7角应用程序):
this.userService.updateUser(data).pipe(
tap(() => {bla bla bla})
).subscribe(
this.handleUpdateResponse.bind(this),
this.handleError.bind(this)
);
不知道我应该使用什么以及如何...
谢谢!
subscribe
不会被弃用,只会弃用您正在使用的变体。在将来,subscribe
将只接受一个参数:next
处理程序(函数)或观察者对象。
所以在你的情况下你应该使用:
.subscribe({
next: this.handleUpdateResponse.bind(this),
error: this.handleError.bind(this)
});
请参阅以下GitHub问题:
也许有趣的是,observer
对象也可以(仍然)包含complete()
方法和其他附加属性。例:
.subscribe({
complete: () => { ... }, // completeHandler
error: () => { ... }, // errorHandler
next: () => { ... }, // nextHandler
someOtherProperty: 42
});
这样,省略某些方法就容易多了。使用旧的签名,有必要提供undefined
并坚持方法的顺序,现在它更清楚,例如只提供下一个完整的处理程序。
如果您有一个可以代表两种不同类型Observable<T> | Observable<T2>
的对象,则可能会出现此错误。
例如:
const obs = (new Date().getTime() % 2 == 0) ? of(123) : of('ABC');
您可能会惊讶于以下内容会给您错误Use an observer instead of a complete callback
和Expected 2-3 arguments, but got 1.
obs.subscribe(value => {
});
这是因为它可能是两种不同类型中的一种,编译器不够智能,无法协调它们。
您需要更改代码以返回Observable<number | string>
而不是Observable<number> | Observable<string>
。这种微妙之处取决于你正在做什么。