取消订阅服务OnDestroy?

时间:2017-10-11 02:59:44

标签: angular

以这种方式订阅时:

getRecipes(): void {
    this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes);
  }

我打电话给' getRecipes();'在'ngOnInit()'中,我是否必须以某种方式取消订阅或者是否需要处理?我是否需要将OnDestroy函数添加到我的组件并取消在那里或?根据我的阅读,取消订阅非常重要

1 个答案:

答案 0 :(得分:2)

试试这样:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Rx';

export class Component implements OnInit, OnDestroy {
    private subscription: Subscription;
    ngOnInit() {
        this.subscription = this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}