如何在Resolve Angular 2中获取Route Params

时间:2017-01-27 00:17:46

标签: angular angular2-routing

我试图让我的路线参与决心。 但是它并不包含参数,但是当我从组件内部使用activatedRoute时它确实有效。我认为这是因为路线在决心内没有改变。我如何让它工作?

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
    }
},

3 个答案:

答案 0 :(得分:10)

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

resolve(route: ActivatedRouteSnapshot) {
    console.log(route.data); // {title: "Post"}
}

答案 1 :(得分:2)

resolve(route: ActivatedRouteSnapshot) {
   console.log(route.data.title); // "Post"
   console.log(route.params['slug']) // prints the dynamic parameter value
}

答案 2 :(得分:0)

resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.property.getProperty(parseInt(route.paramMap.get(' ')));
}