【问题标题】:How to unsubscribe from observable created by an Angular Service [duplicate]如何取消订阅由 Angular 服务创建的 observable [重复]
【发布时间】:2019-12-20 23:23:21
【问题描述】:

我对 Angular 还是很陌生,我的问题可能看起来很基础,但我们将不胜感激。我目前正在编写一个应用程序来教自己一些真正的开发技能。在我的应用程序中,我有一个 Angular 组件,它导入我编写的提供数据的服务。

这是我的组件

@Component({
  selector: 'music-instrument-list',
  templateUrl: './instrument-report.component.html',
  styleUrls: ['./instrument-report.component.css']
})
export class InstrumentReportComponent implements OnInit, OnDestroy {
    
    constructor(public apiService: ApiService) {}
    public availableInstruments: any[];

    ngOnInit() {
        this.apiService.getInstruments().subscribe((result) => {
            this.availableInstruments = result;
        });
    }

    ngOnDestroy() {
    // how do I unsubscribe?
    }
}

这很简单,但如果我尝试将this.apiService.getInstruments.unsubscribe() 添加到ngOnDestroy 块中,我会收到错误消息,即 Property 'unsubscribe' 在 type => Observable' 上不存在。我什至考虑在.subscribe() 之后添加.unsubscribe() 之类的链接,但这只会让我的页面挂起。我也没有错误。有人可以告诉我如何最好地退订吗?我是否需要将 api 调用分配给一个变量,然后在 ngOnDestroy 块中的变量名称上使用 .unsubscribe()

【问题讨论】:

    标签: angular angular-observable rxjs-observables


    【解决方案1】:
    @Component({
      selector: 'music-instrument-list',
      templateUrl: './instrument-report.component.html',
      styleUrls: ['./instrument-report.component.css'],
    })
    export class InstrumentReportComponent implements OnInit, OnDestroy {
      subscription: Subscription;
      constructor(public apiService: ApiService) {}
      public availableInstruments: any[];
    
      ngOnInit() {
        this.subscription = this.apiService.getInstruments().subscribe((result) => {
          this.availableInstruments = result;
        });
      }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    

    【讨论】:

      【解决方案2】:

      为避免内存泄漏,您可以从ObservableSubscription 取消订阅。 例如:

          subscription: Subscription;
      
          ngOnInit() {
              this.subscription = this.apiService.getInstruments().subscribe((result) => {
                  this.availableInstruments = result;
              });
          }
      
          ngOnDestroy() {
              this.subscription.unsubscribe();
          }
      

      或使用async 管道:

      打字稿:

          instruments$;
      
          ngOnInit() {
              this.instruments$= this.apiService.getInstruments().subscribe((result) => {
                  this.availableInstruments = result;
              });
          }
      

      HTML:

          <li *ngFor="let instr of instruments$ | async">
              {{ instr | json }} 
          </li>
      

      【讨论】:

      • 谢谢,它对我有用!
      【解决方案3】:

      在 Angular 中处理观察者的最新和更简洁的方法是在模板组件中使用异步管道,它将订阅和可观察对象的销毁委托给容器框架。 您可以在此处找到更详细的示例(角度文档): https://angular.io/api/common/AsyncPipe

      【讨论】:

        【解决方案4】:

        您不应取消订阅自动完成的 observables(例如 Http、调用)。但是有必要取消订阅像Observable.timer() 这样的无限可观察对象。 unsubscribe from Angular HTTP calls

        至于一般退订,这是一个重复的问题,在这里回答 How to unsubscribe for an observable

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-12
          • 1970-01-01
          • 2017-04-13
          • 2018-02-14
          • 1970-01-01
          相关资源
          最近更新 更多