【发布时间】: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