Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Route data into App Component in Angular 2

Tags:

I have defined some route data in my app routing module like below:

    const appRoutes:Routes = [
  {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]

I want to get the data globally so that I can use appRoutes in app.component.ts to get the URL redirection related information as below:

export class AppComponent {
  title = 'Welcome';
  constructor(public router: Router, public authenticationService: AuthenticationService) {
    this.router.events.subscribe(event => {
        console.log("Url",event.urlAfterRedirects);
        console.log("Page Name", router[PageName]); //Not working
      }

I tried injecting ActivatedRoute but it's not getting updated after each redirection.

Is there anyway, where I can configure page name and get it in global app.component.ts.

like image 621
user1188867 Avatar asked Apr 20 '17 07:04

user1188867


People also ask

What would you use in Angular 2 to define routes?

Instead of “href” attribute of anchor tag, we use the “routerLink” attribute of Angular. The routerLink attribute allows us to link to a specific route of the Application.


2 Answers

Try to filter and loop your events instead of subscribe

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        this.title = route.root.firstChild.snapshot.data['PageName'];
    });
}

Please check the following working demo: https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

like image 118
Hristo Eftimov Avatar answered Sep 28 '22 01:09

Hristo Eftimov


If you had statically routed using Router object like below:

{
  path: '',
  pathMatch: 'full',
  component: NameComponent,
  data: { variableName: 'variableValue' }
},

On ngOnInit() you can use ActivatedRoute object to recover the data you passed from Router definition:

ngOnInit() {
  this.localVariable = this.route.snapshot.data['variableName'];
}

Obs: I am using Angular 5!

like image 27
Pablo Avatar answered Sep 28 '22 01:09

Pablo