As I am new to angular 2/4 I am having trouble setting up a new application as per my need.
I am trying to build an application which will be called for from some anothe
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor( private route: ActivatedRoute, private router: Router ) {}
ngOnInit(): void {
this.router.events.subscribe(val => {
if (val instanceof RoutesRecognized) {
if (val.state.root.firstChild.params.id) {
localStorage.setItem('key1', val.state.root.firstChild.params.id);
localStorage.setItem('key2', val.state.root.firstChild.params.id2);
}
console.log('test', val.state.root.firstChild.params);
}
});
}
}
For one time value use like below:
import { Router , ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}
ngOnInit() {
console.log(this.route.snapshot.params['username']);
}
The above snapshot method. Snapshot method just gives you result once you initiate the component. So this will keep on working if you change the route or destroy the component and initiate again only.
A solution for the downvoters and/or anyone who want to update the param each time the route change will be:
import { Router , ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}
ngOnInit() {
// Works first time only
console.log(this.route.snapshot.params['username']);
// For later use, updates everytime you change route
this.route.params.subscribe((params) => {console.log(params['username'])});
}
This post solved problem. here
I needed to create a separate component Root and in that i kept my Router-Outlet and added this component as my bootstrap module and it worked!! I do not have reputation more than 50 if i had than i would thanked him on the same post. Thanks man @Fabio Antunes