Do you have to unsubscribe from a QueryList in a component?

只愿长相守 提交于 2020-02-21 11:06:15

问题


When using the @ContentChildren or @ViewChildren decorators to listen for changes to DOM elements. Do I have to unsubscribe from the QueryList?

For example:

@Component({...})
export class ParentComponent implements AfterContentInit {
    @ContentChildren(ChildComponent)
    public children: QueryList<ChildComponent>;

    public ngAfterContentInit(): void {
        this.children.changes.subscribe(() => ....);
    }
}

Would the above be a problem?

Updated:

The reason I'm asking is that we don't have to unsubscribe to @Output decorators. These are automatically unsubscribed by the component when it is destroyed.

I can not find any documentation which says this is the same for the QueryList.


回答1:


You don't have to unsubscribe from QueryList. It does it for you.

See here: https://github.com/angular/angular/blob/7d137d7f8872a6fba72668e32f9baf2c5dcfc48b/packages/core/src/linker/query_list.ts#L115

As a general rule, I unsubscribe when Observable stays alive after Component destroyal. Works in most scenarios.




回答2:


As a general rule, it's good to unsubscribe from things that you have subscribed to when your component is destroyed. In Angular, you can do this in your ngOnDestroy method.

import { Subscription } from 'rxjs';

@Component({...})

export class ParentComponent implements AfterContentInit, OnDestroy {
    @ContentChildren(ChildComponent)
    public children: QueryList<ChildComponent>;
    private childrenSubscription: Subscription;

    public ngAfterContentInit(): void {
        this.childrenSubscription = this.children.changes.subscribe(() => ....);
    }

    public ngOnDestroy(): void {
        this.childrenSubscription.unsubscribe();
    }
}


来源:https://stackoverflow.com/questions/51391935/do-you-have-to-unsubscribe-from-a-querylist-in-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!