2

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

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.

@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. 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.

Anjil Dhamala
  • 1,544
  • 3
  • 18
  • 37

1 Answers1

0

Using snapshot.params is only good when the component first loads. you should instead, subscribe to the param's observable on your ngOnInit.

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

also instead of this hack:

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

you should navigate properly:

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

Stavm
  • 7,833
  • 5
  • 44
  • 68
  • I like the second suggestion. I'll do that. But in regards to resolve, isn't the resolver supposed to be created before the component and hence can look at the current url and resolve any async operations before the component loads? What's the point of resolver if it can't resolve back the data on a browser refresh? I don't need to use snapshot. I can subscribe to params. However, even that never gets the actual route params. – Anjil Dhamala Feb 19 '19 at 16:41
  • I see my problem. I injected ActivatedRoute service instead of using ActivatedRouteSnapshot parameter that Angular passes to the resolve() method. – Anjil Dhamala Feb 19 '19 at 18:22