Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度:我应该取消订阅switchMap吗_Angular_Rxjs - Fatal编程技术网

Angular 角度:我应该取消订阅switchMap吗

Angular 角度:我应该取消订阅switchMap吗,angular,rxjs,Angular,Rxjs,我有以下组件: @Component({...}) export class AppComponent implements OnInit, OnDestroy { destroy$ = new Subject(); update$ = new Subject(); result: Result; constructor(service: Service) { } ngOnInit() { update$.pipe( takeUntil(thi

我有以下组件:

@Component({...})
export class AppComponent implements OnInit, OnDestroy {

  destroy$ = new Subject();
  update$ = new Subject();

  result: Result;

  constructor(service: Service) {
  }

  ngOnInit() {
    update$.pipe(
      takeUntil(this.destroy$),
      switchMap(() => this.service.get())
    ).subscribe(result => this.result = result);

    this.refresh();
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  refresh() {
    this.update$.next();
  }

}
这种方法正确吗?或者我应该在
switchMap
之后调用
takeUntil(this.destroy$)

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);
或者我应该叫它两次

update$.pipe(
  takeUntil(this.destroy$),
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);

通常您希望
takeUntil
应该是最后一个操作符。在您的情况下,这是正确的方法:

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);

最干净的方法是在
switchMap
之后调用
takeUntil

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);
这将防止对订阅的任何排放。如果在之前添加
takeUntil
,则
switchMap
订阅将发出值,直到
project
函数返回的可观察值完成,这可能永远不会完成(取决于您的服务代码)


switchMap
之前和之后都不需要调用
take,因为
switchMap
在其自身被取消订阅时,会从可观察的源(在
switchMap
之前的所有内容)取消订阅。

它会同时从主题和服务结果中取消订阅吗?是的,它会同时从两者中取消订阅