简体   繁体   English

Angular Routing Route Params是子组件的解析器中的空对象

[英]Angular Routing Route Params is empty object in Child Component's Resolver

This is my route setup. 这是我的路线设置。

const appRoutes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'get',
    canActivateChild: [CanActivateOrder],
    children: [
      {
        path: '',
        redirectTo: 'confirm',
        pathMatch: 'full'
      },
      {
        path: 'confirm',
        component: ConfirmComponent
      },
      {
        path: 'book/:id',
        resolve: {
          pageData: BookResolver
        },
        component: BookComponent
      }]
  },
  {
    path: '**',
    redirectTo: ''
  }
];

This is my router call to navigate to book/:id from /confirm 这是我的路由器呼叫,用于从/confirm导航到book/:id

this._router.navigate(['get/book', 1234]);

In my BookResolver, if I try to access any of the params under ActivatedRoutes' snapshot, I get empty object. 在我的BookResolver中,如果尝试访问ActivatedRoutes快照下的任何参数,则会得到空对象。

@Injectable()
export class BookResolver implements Resolve<any> {

  constructor(private _activatedRoute: ActivatedRoute) {}

  resolve(): Observable<Book> {
    console.log(this._activatedRoute.snapshot.params);
    //This is {}
  }

However, If I try to access the same thing from the BookComponent, I get the desired output. 但是,如果我尝试从BookComponent访问相同的内容,则会得到所需的输出。 As in,

export class BookComponent {
  constructor(ac: ActivatedRoute){
    console.log(ac.snapshot.params);
    //this is {id: 1234}
  }
}

Where exactly is my route setup going wrong? 我的路线设置到底在哪里出错? I'm assuming the setup is at fault here. 我假设这里的设置有问题。 Let me know if you need more clarity on the question. 让我知道您是否需要进一步澄清这个问题。

Here's a stackblitz reproduction . 这是堆积如山的复制品

Using snapshot.params is only good when the component first loads. 仅在首次加载组件时,使用snapshot.params才有用。 you should instead, subscribe to the param's observable on your ngOnInit . 您应该改为在ngOnInit上订阅可观察的参数。

this.ac.params.subscribe(
  (params: Params) => console.log(params);
);

also instead of this hack: 也代替这个hack:

this._router.navigate(['get/book', 1234])

you should navigate properly: 您应该正确导航:

this._router.navigate(['get', 'book', 1234])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM