Muizz Mahdy
Muizz Mahdy

Reputation: 808

Angular/Typescript: Accessing object data in constructor

Trying to access an object's data in a constructor returns an "undefined" object. It works on the ngOnInit() function, but the data (going to get reset) is needed every time the component starts.

   import { Component, OnInit, Input } from '@angular/core';
   @Input() data: any;


   constructor(dataService: DataService)
   {
     console.log(this.data); // undefined
   }


   ngOnInit()
   {
     console.log(this.data) // works here
   }

Upvotes: 0

Views: 1152

Answers (2)

Oscar Paz
Oscar Paz

Reputation: 18292

You can't access the value of a component input inside its constructor, except for the initial value you assign to it.

Why?

Well, easy: Angular must create the component first (by invoking its constructor). Only then can it set the inputs. If you try to use an input property in the constructor, obviously it will be undefined.

In your case, you should use the value in ngOnInit, or, if you really need it in the constructor, retrieve it in another way (by using an injected service, a global shared object ...).

Upvotes: 1

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Have you read this documentation?

It said:

After creating a component/directive by calling its constructor, Angular calls the lifecycle hook methods in the following sequence at specific moments

And then it lists all methods according to the order of excecution.

You can read the full documentation of lifecycle hook, it is good to know this when we start developing application using Angular.

Upvotes: 1

Related Questions