I am writing an angular application for a landing page for a SaaS application. The SaaS is redirecting to the angular application with the URL http://localhost:4200/token=<token>
and angular quickly changes to the home component http://localhost:4200/#/
.
I need to get the value of <token>
to use in the code. How do I copy the initial URL in an angular application?
CodePudding user response:
you can use the angular router to get the token if its formatted as you have depicted.
import angular router from @angular/router.
constructor(router:Router){}
yourRoute ?:string;
ngOnInit(){
this.yourRoute = this.router.url.split('/').pop();
}
for future reference:
if this doesn't work you can use the activated route library.
let me know.
CodePudding user response:
- In your AppRoutingModule:
import { Routes } from '@angular/router';
const routes:Routes = [
{
path:'',
component: MainComponent, // Your main component, wich is going to get the token
pathMatch: ‘full’
},
{
path:'/:token',
component: MainComponent, // Your main component, wich is going to get the token
},
... // Your others routes:
{
path:'xxx',
component: XxxComponent
},
{
path:'**',
redirectTo: ''
}
]
NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
- Remember to import in your AppModule your AppRoutingModule:
...
import { AppRoutingModule } from './app-routing.module';
...
imports: [
...
AppRoutingModule,
...
],
- In your MainComponent, wich is going to get the token
import { ActivatedRoute } from '@angular/router';
token: string
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit(): void {
this.token = this.activatedRoute.snapshot.paramMap.get('token');
// If you were to receive countinuosly tokens :
// this.activatedRoute.params.subscribe( _token => this.token = _token);}
Finally, you only have to call angular like this:
**http://localhost:4200/token**