Reputation: 390
Currently, I'm implementing an embed chat system which allows user to embed the client chat app to their website. The client chat app using angular 2 (version 4). There are 2 type of user, agent and client. Client will be identified using their credential and and website ID (which is created when agent register his website). Therefore, I need to pass the website ID into each request from client app. I plan to put this website ID into url as a query param. However I cannot get this value when app bootstrapping.
The URL looks like this:
http://localhost:3000?site=123456
Here is the app routing, when initializing, the root path will be redirected based on the login state:
const routes: Routes = [
{
path: '',
redirectTo: '/chat',
pathMatch: 'full'
}
];
And in the app component, I tried catching the query param like this:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {
ActivatedRoute, Router, RouterState,
RouterStateSnapshot
} from "@angular/router";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
title = 'app works!';
constructor(private router: Router,
private activatedRoute: ActivatedRoute) {
//
}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(p => console.log(p)); // result empty
console.log(this.router.routerState.snapshot.root.queryParams); // result empty
}
}
Assume that user already logged in, the app will redirect to http://localhost:3000/chat and the queryParams I try to catch return empty (in ngOnInit method), the query param in url also gone like http://localhost:3000/chat. If I place the query params after slug /chat (example http://localhost:3000/chat?site=123456) I can catch the value and the query param remains in url. I'm suspecting the redirect causing this, can anyone point out where I went wrong. Thank you.
Upvotes: 2
Views: 2281
Reputation: 65
You can use Guard to request a route before the router changes
The function canActivate can get activateRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot As parameters, the value of the query param is found in state.root.queryParams.site
Do not forget to return true value from the function
Upvotes: 1
Reputation: 65
You have to set the router Module to use hash and it will work
in app.module
replace RouterModule
RouterModule.forRoot(routes, {useHash:true}),
Upvotes: 1