如何取消订阅 Angular 服务创建的可观察对象

New*_*lar 1 angular angular-observable rxjs-observables

我对 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?
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*pUp 5

为了避免内存泄漏,您可以Observable通过取消订阅Subscription。例如:

    subscription: Subscription;

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

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
Run Code Online (Sandbox Code Playgroud)

或使用async管道:

打字稿:

    instruments$;

    ngOnInit() {
        this.instruments$= this.apiService.getInstruments().subscribe((result) => {
            this.availableInstruments = result;
        });
    }
Run Code Online (Sandbox Code Playgroud)

HTML:

    <li *ngFor="let instr of instruments$ | async">
        {{ instr | json }} 
    </li>
Run Code Online (Sandbox Code Playgroud)