Angular Memory Management

Discussão em 'Angular' iniciado por buchipper, Abril 13, 2025.

  1. buchipper

    buchipper Guest

    I am trying to understand if there is an easy way to unsubscribe automatically from observables/subjects.

    For example, lets say I have a component

    @Component({
    selector: 'mySelector',
    template: `<div>Hello World</div>`,
    styleUrls: [ 'myStyles.scss' ]
    })
    export class MyComponent {
    constructor(private service: MyService){ }
    ngOnInit()
    {
    /// Forgot to store subscription!!!!!!!!!!!!!!!
    this.service.clickStream$.subscribe( clickEvent => {
    DoSomething();
    } );
    }

    DoSomething()
    {
    console.log('DoSomething');
    }

    }



    Here the developer has forgotten to store the subscription or call unsubscribe on the subscription. Ideally, should have stored the subscription and called subscription.unsubscribe() in the ngOnDestroy.

    In C++, we have smartpointers like shared_ptr/auto_ptr. Is there anything similar in Angular/Typescript that automatically unsubscribes in case a developer forgets.

    Continue reading...

Compartilhe esta Página