Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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 订阅/取消订阅最佳实践_Angular_Typescript - Fatal编程技术网

Angular 订阅/取消订阅最佳实践

Angular 订阅/取消订阅最佳实践,angular,typescript,Angular,Typescript,我现在想知道如何订阅和取消订阅。关于这个主题有很多东西,所以我对这一切都有点迷茫 我应该什么时候取消订阅?如果我永远都不退订他们会怎么样?我从未遇到任何来自reliquat订阅的错误 有没有一种方法可以自动取消订阅组件/应用程序中的所有内容,这样我就不必按订阅声明1个属性?这可能非常烦人: @Component({ selector: 'subscriptionTest', template: `...`, }) export class SubTestComponent { fir

我现在想知道如何订阅和取消订阅。关于这个主题有很多东西,所以我对这一切都有点迷茫

我应该什么时候取消订阅?如果我永远都不退订他们会怎么样?我从未遇到任何来自reliquat订阅的错误

有没有一种方法可以自动取消订阅组件/应用程序中的所有内容,这样我就不必按订阅声明1个属性?这可能非常烦人:

@Component({
  selector: 'subscriptionTest',
  template: `...`,
})
export class SubTestComponent {
  first;
  second;
  third;

  constructor(private remote: RemoteService){}

  ngOnInit() {
    this.first = remote.getSomeData().subscribe(data => // do something);
    this.second = Observable.interval(500).subscribe(event => // do something);
    this.third = remote.getSomeOtherData().subscribe(data => // do something);

  }

  ngOnDestroy() {
    this.first.unsubscribe();
    this.second.unsubscribe();
    this.third.unsubscribe();
  }

}

takeUntil
操作符是“自动”取消订阅任何订阅的简单方法,例如:

@Component({...})
export class AppComponent implements OnInit, OnDestroy {
  destroy$: Subject<boolean> = new Subject<boolean>();

  constructor(private apollo: Apollo) {
  }

  ngOnInit() {
    this.apollo.watchQuery({
        query: gql`
        query getAllPosts {
          allPosts {
            title
            description
            publishedAt
          }
        }
      `
      })
      .takeUntil(this.destroy$)
      .subscribe(({data}) => {
        console.log(data);
      });
      remote.getSomeData().subscribe(data => // do something);
      Observable.interval(500).subscribe(event => // do something);
      remote.getSomeOtherData().subscribe(data => // do something);
  }

  onStartInterval() {
    Observable
      .interval(250)
      .takeUntil(this.destroy$)
      .subscribe(val => {
        console.log('Current value:', val);
      });
  }

  ngOnDestroy() {
    this.destroy$.next(true);
    // Now let's also unsubscribe from the subject itself:
    this.destroy$.unsubscribe();
  }
}
@组件({…})
导出类AppComponent实现OnInit、OnDestroy{
销毁$:主题=新主题();
建造师(私人阿波罗:阿波罗){
}
恩戈尼尼特(){
这是apollo.watchQuery({
查询:gql`
查询getAllPosts{
所有职位{
标题
描述
出版
}
}
`
})
.takeUntil(此.destroy$)
.subscribe({data})=>{
控制台日志(数据);
});
remote.getSomeData().subscribe(数据=>//执行操作);
可观察的.interval(500).subscribe(事件=>//做某事);
remote.getSomeOtherData().subscribe(数据=>//执行操作);
}
onStartInterval(){
可观察
.间隔(250)
.takeUntil(此.destroy$)
.订阅(val=>{
console.log('当前值:',val);
});
}
恩贡德斯特罗(){
this.destroy$next(true);
//现在让我们也退订主题本身:
此.destroy$.unsubscribe();
}
}
您不必声明每个订阅,只需在每个订阅上添加
.takeUntil(this.destroy$)
操作符即可

资料来源:


一篇关于订阅的精彩文章:

您可以使用第三方插件,如如果您不想重复自己的内容,请使用超级类:

/**
*  Unsubscribe from any Observable using takeUntil and this.destroy$
*      someObservable.pipe( // lettable operators in rxjs ^5.5.0
*          ...
*          takeUntil(destroy$)
*      )
*      .subscribe(....
**/
export class Destroyer implements OnDestroy {
    destroy$: Subject<boolean> = new Subject<boolean>();

    ngOnDestroy() {
        // Unsubscribe from whatever used takeUntil(destroy$)
        this.destroy$.next(true);
        // Now let's also unsubscribe from the subject itself:
        this.destroy$.unsubscribe();
    }
}

最好的方法是使用Subscription类

为此,您将在组件中创建一个变量,如下所示

private subs: Subscription = Subscription.EMPTY;
this.subs.add(this.route.data.subscribe(...
然后像这样使用

private subs: Subscription = Subscription.EMPTY;
this.subs.add(this.route.data.subscribe(...

在Ngondestory()中进行一个独特的调用,如

this.subs.unsubscribe();

这可能会有帮助。这也是gud关于如何以及何时取消订阅的另一篇文章。哦,谢谢!有了这个库,我还必须声明每个订阅?我更喜欢不使用lib,因为我可以用本机代码做一些事情,最好的方法是使用Subscription类。您可以创建一个变量,如subs:Subscription=Subscription.EMPTY;然后。。。this.subs.add(this.route.data.subscribe(…或this.subs.add(this.clientService.login(this.username,this.password)).subscribe(…并在您的ngOnDestroy()中进行唯一调用,如以下.subs.unsubscribe();在Angular中,您没有多重继承,因此此方法在其他需要扩展的实现中可能很困难。例如,就像许多Angular类的一个实例。这对我不起作用。
this.subs=Subscription.EMPTY;this.sub=foo$.subscribe();this.subs.add(this.sub);console.log(this.sub.closed);
.Then
this.sub.closed
始终是
true
,即使我没有调用
this.subs.unsubscribe();
此解决方案可以将
subs:Subscription=Subscription.EMPTY;
替换为
private subs=new Subscription();