Angular 11:订阅已弃用:改用观察者?

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

我的 tslint 疯了?它会为我在整个应用程序中所做的每个订阅发出警告。不管我使用旧语法还是新语法,它仍然说订阅已弃用...如何编写不会被弃用的订阅?

直到今天还可以:

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

我尝试了新的语法但没有做任何改变:

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

这正是它所说的:

(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)

那么我现在该如何订阅呢?

回答您的问题“那么我现在该如何订阅”: https://rxjs-dev.firebaseapp.com/guide/observer 就是这个。它易于使用并且与之前所做的非常相似,只是它实际上现在接受一个具有 3 个键的对象(观察者):下一个、错误、完成。

我们像 2 天前在工作中进行了同样的讨论,虽然你 can/should 使用观察者,但弃用似乎是虚惊一场。 (我们认为我们必须改变 ~900 订阅):

这是在 rxjs github 页面上创建的关于此问题的问题:https://github.com/ReactiveX/rxjs/issues/6060

开发人员在其中说这是由于打字稿错误造成的:https://github.com/microsoft/TypeScript/issues/43053

这个错误已经在 3 天前修复了,但我不确定它是否已经在最新版本中:

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

我刚刚在 VS Code 扩展选项卡中查找了 TSLint (v1.3.3)。它说:

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

当我禁用 TSLint 并安装 ESLint 时,所有与订阅相关的警告都消失了。

干杯!

更好的解决方法

我遇到了同样的问题,我通过使用更清晰的方式解决了它。

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

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