-2

I have a routerlink in a in Angular. I am trying to send some data along with the routerlink. This is the html code of the component:

html code:

<a routerLink="/register" [queryParams]="{ selRole: 1 }">Register Now</a>

In my component:

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
    });
    console.log(this.selRole)
}

But I always keep getting a 0. What exactly am I doing wrong here?

JackSlayer94
  • 805
  • 3
  • 16
  • 38

2 Answers2

1

Try to use the same format in [routerLink] and [queryParams] even though it is not causing the issue,

<a [routerLink]="['/register']" [queryParams]="{ selRole: 1 }">Register Now</a>

also place your console.log after assigning the params to selRole which is the root cause

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

console.log(this.selRole) is run before the queryParams.subscribe is called.

The queryParams is an observable and you are subscribing to that observable. You will only get the value once that is called.

To get the value you can move the console.log into the subscribe block.

ngOnInit() {
    this.route.queryParams
        .subscribe(params => {
            this.selRole = params['selRole'] || 0;
            console.log(this.selRole)
    });
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nipuna-g
  • 6,252
  • 3
  • 31
  • 48