【问题标题】:Angular 2 : How to get params on resolveAngular 2:如何在解析时获取参数
【发布时间】:2017-05-18 07:43:09
【问题描述】:

溃败策略:

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 服务中获取参数。

问题:我可以从路由器服务中获取参数吗?

简介:尝试在 Resolve Injectable 上获取路由参数,因为在该阶段路由未激活,我无法获取参数。

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

在任意子组件中激活路由时成功获取参数:

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

            })

    });
}

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

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

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

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


    编辑:您还可以查看 Resolve

    的文档

    【讨论】:

    • 使用 route.params.id 会导致另一个错误“类型 '{ [key: string]: any; }' 上不存在属性 'id'。” Angular -shared.d.ts 导出声明类型 Params = { [key: string]: any; };
    • 那你用route.params['id']试过了吗?
    • 很高兴你让它工作了:-) 当你使用['id']时,类型错误也应该消失了
    【解决方案2】:

    我们需要在解析器方法而不是构造函数中传递依赖

      resolve(route: ActivatedRouteSnapshot) {
    
        console.log(route.params);// you can see the log and use it
    
        return this.apiService.getItems(route.params.params1).catch(() => {
           return Observable.empty();
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多