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

Far*_*ris 5 angular2-routing angular

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}

    ]
}
Run Code Online (Sandbox Code Playgroud)

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

            });
    });
    }
Run Code Online (Sandbox Code Playgroud)

我知道:我们通常从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) => {

            })

    });
}
Run Code Online (Sandbox Code Playgroud)

ben*_*boe 9

SingleRtoResolve应该的implements Resolve<T>.然后你只需要你的数据服务(RtoService我猜)constructor() {}.不需要Router或在ActivatedRoute这里,因为你resolve()会得到一个ActivatedRouteSnapshot和一个RouterStateSnapshot.所以resolve()看起来会像那样:

  resolve(
    route: ActivatedRouteSnapshot, state: RouterStateSnapshot
  ): Promise<any> {
    return ...
  }
Run Code Online (Sandbox Code Playgroud)

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


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