neptune
neptune

Reputation: 1261

Ui router resolve variable remain undefined in component constructor

I have this UI router state with a component attached to it:

export const exchangeState = {
    name: 'exchange',
    url: '/exchange',
    component: ExchangeMainComponent,
    resolve: [
        {
            token: 'fromResolve',
            resolveFn: () => {
                return 'string from resolve';
            }
        }
    ]
};

In component's constructor I trying to access fromResolve but it returns undefined. This is the component:

@Component({
  selector: 'app-exchange-main',
  templateUrl: './exchange-main.component.html',
  styleUrls: ['./exchange-main.component.css']
})
export class ExchangeMainComponent implements OnInit {
    @Input('fromResolve') fromResolve: string;
    constructor() {
        console.log(this.fromResolve); // <- undefined
    }
    ngOnInit() {
    }
}

fromResolve showing up correctly in the view.

How can I have it's value in the constructor?

Upvotes: 1

Views: 162

Answers (2)

AVJT82
AVJT82

Reputation: 73377

@Input values are first available in OnChanges life cycle hook. The order of execution is...

constructor -> OnChanges -> OnInit ....

So you can either access it in OnChanges or OnInit, but not in the constructor.

Upvotes: 1

pioro90
pioro90

Reputation: 694

If you are using Angular RouterModule you should do something like this

fromResolve: string;
constructor(private router: ActivatedRouter) {
 this.route.data
  .subscribe((data: { fromResolve: string}) => {
    this.fromResolve= data.fromResolve;
  });
}

You should modify you router in a way which is described here:

Fetch data before navigating

Upvotes: 0

Related Questions