Sunday, November 18, 2018

ngOnDestroy lifecycle hook


The ngOnDestroy lifecycle hook gets executed just before Angular destroys the directive/component. Use this event to unsubscribe Observables and detach event handlers to avoid memory leaks.  It is the perfect place to clean the component. Let us see on how to use this lifecycle hook with a simple example.

Similar to our ngOnOnit example, we have a service call using an observable to make a http ajax call to get data from a service, in this example we will use the ngOnDestroy hook to unsubscribe the observable and do a cleanup when the component in unloaded.

import { Component, OnInit, OnDestroy  } from '@angular/core';
import { UserdataService } from './userdata.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy  {
  message: string;
  userList;
  errorMessage: string;
  httpSubscription;
  constructor(private svcData: UserdataService) { }

  ngOnInit() {
    this.message = 'Hello from Parent.'
    this.user.name = 'Hello User'
    this.getData();
  }

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

  getData () {
    this.httpSubscription = this.svcData.getUsers().subscribe(
      data => this.userList = data,
      err => this.errorMessage = err.status + ' - ' + err.statusText
    );   
  }
}


Search Flipkart Products:
Flipkart.com

No comments: