13

What are the differences between constructor, ionViewDidLoad and ngOnInit methods. What actions are appropriate in each case.

ifeoluwa king
  • 531
  • 1
  • 8
  • 19
  • 1
    I don't know `ionViewDidLoad` but the others are explained in http://stackoverflow.com/questions/35845554/angular-2-component-constructor-vs-oninit – Günter Zöchbauer Nov 16 '16 at 10:29
  • 1
    ionViewDidLoad is an ionic method that is similar to ngOnInit() in angular2. To know more about it check http://ionicframework.com/docs/v2/api/navigation/NavController/ – AishApp Nov 16 '16 at 10:39
  • 1
    http://ionicframework.com/docs/v2/api/navigation/NavController/#lifecycle-events to be exact. Guess your question is answered with these 2 links – Ivar Reukers Nov 16 '16 at 12:17
  • I also would love to know the difference as both work in an Ionic2 application. Should we not be using ngOnInit for some reason? – Gabe O'Leary Feb 14 '17 at 04:24
  • 1
    @GabeO'Leary You can use whichever you want, however be consistent. I suggest you use `ionViewDidLoad()` and `ionViewWillUnload()` instead of the angular's `ngOnInit()` and `ngOnDestroy()`. If the lifecycle events in ionic are not suitable for your usecase, by all means use the angular events. – Mihai Tomescu Mar 21 '17 at 20:19

4 Answers4

4

Constructor

A constructor is not an Angular feature, it is called by the Javascript engine. Well, written in TypeScript but it is an ES6 concept, it is part of the class lifecycle hook. Therefore it is not a good place to know when Angular has finished initialising its components.

It is the right place to do any dependency injection.

ngOnInit

The ngOnInit is an Angular lifecycle hook. It is executed when Angular has finished setting up the component. This means that at this point property bindings are done for example.

It is a good place for initialising some data for the component.

ionViewDidLoad

The ionViewDidLoad is an Ionic navigation lifecycle event. Ionic has a concept of pages. It has some classes related to the navigation logic, the base class for it is NavController. They have a concept of navigation stack, so the pages are basically pushed or popped from the stack. During this process of navigation lifecycle events like ionViewDidLoad are fired up.

ionViewDidLoad is called once the page has been loaded. Pages are cached by default this means this event won't be fired up again if not destroyed.

Considering that it is a good place to put set up code for the page.

References:

Ionic NavControler

Angular Lifecycle Hooks

ES6 Classes

skinny_jones
  • 470
  • 1
  • 5
  • 12
2

Although niks' answer does point out proper lifecycle event firing order, the Angular team recommends against fetching data inside constructors.

But to answer your question, ionViewDidLoad() and ngOnInit() should run at the same times, so they are essentially the same thing; though, ionViewDidLoad() checks for caching:

If a page leaves but is cached, then this event will not fire again on a subsequent viewing.

With that, for anything you don't want cached, but want to load on/before the component gets mounted you should use ionViewWillEnter(), or ionViewWillLoad() for stuff like GET requests. ionViewWillLoad() has yet to be documented.

Desmond
  • 1,532
  • 15
  • 25
1

In respect of ionic2 the constructor: in simple terms we use it to create instance of our plugins, services etc. for example: You have a page(view) where you want to show the list of all students, and you have a json file that contains all the students (this file is your data file) what you have to do is to create a service in this service you will create a method and hit a http.get request to get the json data, so here you need what? http simply do this way:

import {Http} from '@angular/http';
@Injectable()
export class StudentService{
    constructor(public http: Http){}
    getAllStudents(): Observable<Students[]>{
        return this.http.get('assets/students.json')
        .map(res => res.json().data)     
        }
    }

notice the constructor now again if we want to use this service method we will go to our view/page and :

import {StudentService} from './student.service';
import { SocialSharing } from '@ionic-native/social-sharing';
export class HomePage implements OnInit {

  constructor(public _studentService: StudentService, public socialSharing: SocialSharing) {
   }

again notice the constructor here, we are creating an instance of StudentService in constructor and one more thing, we are using socialSharing plugin so to use that we are creating instance of that in constructor as well.

OnInit: this is really amazing thing in ionic2 or we can say in AngularJs2. With the same above example we can see what is ngOnInit is. So you are ready with the service method, now in your view/page you want that student list data available as soon as your view is going to appear, this should be the first operation happend automatically on load, because as the view load the student list should be visible. So the class implements OnInit and you define ngOnInit. Example:

export class HomePage implements OnInit {
...
....
constructor(....){}

ngOnInit(){
    this._studentService.getAllStudents().subscribe(
     (students: Students[]) => this.students = students, 
    )

I hope this explanation clears your doubt about these two. Thanks

Nikhil
  • 417
  • 1
  • 6
  • 16
1

The best practices are:

Use constructor only for dependency injection.

Use ngOnInit to set component properties from static data or navigation data (via NavParams). Template can use the properties set by ngOnInit, i.e., there is no need to use Elvis operator data?.prop to check nullity. It is called only once when a component is created.

Use ionViewDidLoad to set properties only once, similar to ngOniInit. A page only fires this event once when it is created. A page loaded from cache (for example, a page is loaded after a top page is popped) doesn't fire this event. It is ok to use this to set properties of a modal page because modal page is at the top of a stack and is not cached.

Use ionViewWillEnter for setting data every time a page is entered. Unlike ngOninit and ionViewDidLoad, it fires even from cached pages.

For both ionViewDidLoad and ionViewWillEnter events, component properties are not initialized when a page's template is rendered. You should use Elvis operator to check the nullity of an object before access its members.

Ying
  • 2,660
  • 24
  • 23