Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Route Params inside Resolve Angular 2

I am trying to get my route params inside a resolve. However it doesn't contain the params but when I use activatedRoute from inside a component it does work. I think it's because the route hasn't changed yet inside the resolve. How do I get this to work?

post.resolve.ts

@Injectable()
export class PostResolver implements Resolve<any> {
    slug: any;

    constructor(
        private activatedRoute: ActivatedRoute,
        private memoryService: MemoryService,
        ) {}

    resolve() {

        console.log(this.activatedRoute);

        this.activatedRoute.params.subscribe(params => {
            this.slug = params['slug'];
            console.log(this.slug);
            return this.memoryService.getPost(this.slug);
        })

    }
}

app.route.ts

{
    path: 'post/:slug',
    component: PostComponent,
    data: {title: 'Post'},
    resolve: {
        post: PostResolver
    }
},
like image 997
Raymond the Developer Avatar asked Jan 27 '17 00:01

Raymond the Developer


People also ask

How do you access the parameters passed to a route in Angular?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .

How will you extract route parameters?

To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.

How does Angular routing handle route parameters?

To access the route parameters, we use route.snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.


2 Answers

import { Resolve, ActivatedRouteSnapshot } from '@angular/router';

resolve(route: ActivatedRouteSnapshot) {
    console.log(route.data); // {title: "Post"}
}
like image 148
Victor Bredihin Avatar answered Oct 16 '22 16:10

Victor Bredihin


resolve(route: ActivatedRouteSnapshot) {
   console.log(route.data.title); // "Post"
   console.log(route.params['slug']) // prints the dynamic parameter value
}
like image 23
Manichandra Avatar answered Oct 16 '22 17:10

Manichandra