We have already seen how to pass data to a route using route parameters and using Angular query parameters. In this post we’ll see how to pass static data to an Angular route. Static data is configured at the time of defining a route using data property.
For example, here is a route definition with data property-
{path: 'wrongpath', component: PageNotFoundComponent, data :{ message:'Page not found'}},
As you can see with data property you can pass an object having key, value pairs.
This static data is passed as part of route when the PageNotFoundComponent is rendered. In the component you can retrieve the data from the data property of the ActivatedRoute.
Passing static data to route Angular example
Let’s say we have route definitions as given here-
const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'user', component: UsersComponent, children: [ {path: 'add', component: AddUserComponent, canDeactivate: [CanDeactivateGuard]}, {path: 'edit/:userid', component: EditUserComponent, canDeactivate: [UserEditCanDeactivateGuard]} ]}, {path: 'wrongpath', component: PageNotFoundComponent, data :{ message:'Page not found'}}, {path: '', redirectTo:'/home', pathMatch: 'full'}, {path: '**', redirectTo: '/wrongpath'} ];
In the route definitions for the path ‘wrongpath’ there is a data property with a message key and value as 'Page not found'. There is also a wild card route that redirects to this path.
In the PageNotFoundComponent we should have a mechanism to retrieve this static data so let’s see how to do that.
pagenotfound.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Data } from '@angular/router'; @Component({ selector: 'app-pagenotfound', templateUrl: './pagenotfound.component.html' }) export class PageNotFoundComponent implements OnInit{ errorMessage: String; constructor(private route: ActivatedRoute) {} ngOnInit() { //this.errorMessage = this.route.snapshot.data['message']; this.route.data.subscribe((data:Data) =>{ this.errorMessage = data['message']; }) } }
In the ngOnInit() method value for message is retrieved from the data property. Since data is of type Observable so you can subscribe to it. You can also do the same thing using the current route snapshot (commented in the code).
pagenotfound.component.html
<h3> {{ errorMessage }} </h3>
With this setup if you try to access any non-existent route you should be redirected to this PageNotFoundComponent and the message should be rendered.
That's all for this topic Angular Route - Passing Static Data. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Angular Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment