0

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
   }
3
  • 1
    Where does data come from ? How is it defined ? Commented Mar 21, 2018 at 11:36
  • Is the data property defined in the object/class? Commented Mar 21, 2018 at 11:37
  • Data is an input, @Input() data: any; Commented Mar 21, 2018 at 11:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ...).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.