Do you have to unsubscribe from a QueryList in a c

2019-05-06 04:21发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2019-05-06 05:10

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();
    }
}
查看更多
孤傲高冷的网名
3楼-- · 2019-05-06 05:12

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.

查看更多
登录 后发表回答