首页 文章

Angular 2:如何在解决问题上获得参数

提问于
浏览
4

Routs策略:

export const routes = [
{
    path       : 'rto-activation/:id',
    component  : RtoActivationComponent,
    resolve  : {
        'singleRto': SingleRtoResolve
    },
    children   : [
        {path: 'start', component: ActivationStartComponent},
        {path: 'warning', component: WarningComponent},
        {path: 'confirm', component: ConfirmRtoDetailsComponent},
        {path: 'ldWaiver', component: LDWaiverComponent},
        {path: 'payment-schedule', component: PaymentScheduleComponent},
        {path: 'user-reference', component: ReferenceComponent}

    ]
}

SingleRtoResolve:

constructor(private router: Router,
            private route: ActivatedRoute) {
}

resolve() {
    var self = this;
    return new Promise((resolve, reject) => {
        self.subscription = self.route.params.subscribe(
            (param: any) => {
                let id = param[ 'id' ];
               self.rtoService.getRto(null, +id)
                .then((res: any) => {
                    resolve(res)
                })

            });
    });
    }

我知道:我们通常从ActivatedRoute服务获得params .

问题:我可以从路由器服务获得参数 .

简介:尝试在Resolve Injectable上获取路径参数,因为在该阶段路线未激活且我无法获得参数 .

用例:当用户使用某些(:id)打开任何子路由(隐含和显式)时,应该在父路由中解析数据 .

在任何子组件中激活路由时,可以成功获取Params:

ngOnInit() {
let self          = this;
this.subscription = this.route.params.subscribe(
    (param: any) => {
        let id = param[ 'id' ];
        self.rtoService.getRto(null, +id)
            .then((res: any) => {

            })

    });
}

1 回答

  • 7

    你的 SingleRtoResolve 应该 implements Resolve<T> . 然后你只需要 constructor() {} 中的数据服务( RtoService 我猜) . 这里不需要 RouterActivatedRoute ,因为 resolve() 将获得 ActivatedRouteSnapshotRouterStateSnapshot . 所以 resolve() 看起来像那样:

    resolve(
        route: ActivatedRouteSnapshot, state: RouterStateSnapshot
      ): Promise<any> {
        return ...
      }
    

    ..你可以使用 route.params['id'] 来获取你的身份 .


    编辑:您还可以查看 Resolve 的文档

相关问题