Reputation: 1
I'm currently having some problems with the queryParams of an ActivatedRoute. I'm trying to achieve a system where you can call any url with the queryParams = "?token=1234". If this param is provided the AppComponent will use this token to authenticate the user.
The reason for this is that a user will be authenticated within a different application, which will receive a token and forward it to the angular application.
So, in my AppComponent I have the following code:
ngOnInit() {
this._route.queryParams.subscribe(queryParams => {
if (queryParams['token'] != null) {
let data;
this._staffService.getStaffFromToken(queryParams['token']).subscribe(
(response: any) => data = response,
(error: Error) => console.error(error),
() => {
if (data.token != null) {
this._staffService.setLoggedInStaff(data.staff);
this.processLogin();
} else {
this._router.navigateByUrl('/login');
}
}
);
} else {
if (this._staffService.getLoggedInStaff() != null) {
this.processLogin();
} else {
this._router.navigateByUrl('/login');
}
}
});
}
I totally understand the idea of being able to subscribe to these params since it's a SPA and the params might change while using the application.
However, when I go to the following url: http://localhost:4200?token=1234 it navigates immediately to /login. For some reason, when ngOnInit is being called, it doesn't detect the queryParam immediately. When I add a debounceTime of 500 to queryParams, it does work properly but isn't a good solution in my opinion.
Does anyone have some advice? I tried different things but I keep having this problem.
Upvotes: 0
Views: 589
Reputation: 104
When using observable you can't write synchronous code.
Try this.
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
const token = this.activatedRoute.snapshot.params['token'];
Your code ...
}
Upvotes: 0
Reputation: 841
Try to place your code in ngOnChanges()
and review the ng2 Lifecycle
Upvotes: 1