Angular 11 - 订阅已被弃用:使用观察者代替完成回调。

5

我有一个 Angular 应用程序,其中出现了在 subscribe 中被废弃的错误。

这是我的 subscribe

this.route.params.subscribe(params => {
      this.clienteId = +params['clienteId'];
      this.isNew = !this.clienteId;
      if (!this.isNew) {
        this.clienteService.get(this.clienteId).subscribe(c => {
          this.cliente = c;
          this.formNuevo.patchValue(this.cliente);
        });
      }
    });

这是 client-service.ts 文件(get 方法):

public get(idClient: number): Observable<Client> {
      return this.http.get<Client>(`${PREFIX}/${idClient}`);
    }

这是新订阅的错误:

enter image description here

-> 'clienteId' : 使用字符串字面量访问对象是不允许的(no-string-literal)tslint(1)

-> subscribe: 已弃用subscribe:使用观察者替代完整回调(deprecation)tslint(1)

我该如何解决问题并将更改应用于此订阅?


你是否可能在 errorcomplete 回调函数中使用了 null - ruth
错误是由 TSLint 引起的,但我无法修复这个已弃用的问题。调用运行良好。 - synffryd
请提供clienteservice.get的代码。 - Aakash Garg
我已经添加了服务的get方法。 - synffryd
2个回答

14
  1. 使用高阶映射运算符(例如 switchMap)将一个可观察对象映射到另一个。尽量避免嵌套订阅。

  2. "错误"主要是由于在指定其他回调函数的同时,尝试发送其中一个回调函数的订阅,而对于另一个回调函数则指定了 null。例如,对于 nextcomplete 使用 null 作为 error 的值。可以通过发送一个明确指定回调函数的观察者对象来解决这个问题。

请尝试以下操作:

import { iif, NEVER } from 'rxjs';
import { switchMap } from 'rxjs/operators';

this.route.params.pipe(
  switchMap(params => {
    this.clienteId = +params['clienteId'];
    this.isNew = !this.clienteId;
    return iif(                        // <-- `iif` for conditional mapping
      () => !this.isNew,
      this.clienteService.get(this.clienteId),
      NEVER                            // <-- don't emit if condition fails
    );
  })
).subscribe({
  next: c => {
    this.cliente = c;
    this.formNuevo.patchValue(this.cliente);
  },
  error: error => {
    // handle error
  },
  complete: () => {
    console.log('Request complete');
  }
});

我并不真正理解新的做法,但我会继续阅读更多信息,因为在当前订阅中我使用了两个订阅,但现在只有一个。即便如此,订阅仍然给我相同的错误。 - synffryd
@synffryd:你能展示一下错误的截图吗? - ruth
我已经在问题中添加了一张图片,显示了新代码显示的两个错误。 - synffryd
谢谢提供截图。我认为你可能是这个问题的受害者(虽然比较旧):https://github.com/ReactiveX/rxjs/issues/4159#issuecomment-491034939 - ruth
从我所看到的情况来看,订阅目前必须按照以下方式进行:.subscribe({ next: this.handleUpdateResponse.bind(this), error: this.handleError.bind(this) });。在这种情况下有一个订阅,但如果我在另一个订阅内部怎么办? - synffryd
@synffryd: 嵌套订阅通常是不太优雅的,因为它会导致多个开放的订阅。最好使用诸如 switchMap 的映射运算符,就像这里所示。更多信息请参见:https://dev59.com/Rb3pa4cB1Zd3GeqPWQgx#63685990 - ruth

0

我猜测你遇到了这个TypeScript bug,因为你的观察者模式看起来是正确的。该bug已经被修复。我不认为VS Code补丁已经上线了,但应该很快。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接