Home > Software engineering >  Can not get Data from resolver in angular
Can not get Data from resolver in angular

Time:11-30

my resolve:

my resolve

my component:

my component

I haved tried "this.route.data.subscribe" and "this.route.snapshot.data['objectPost']" but i still can get the post's data. Can someone explain whhat is my problem please...? Thanks :D

CodePudding user response:

First thing you have to know about resolving is that route will change when resolved data is ready.

So, this is the flow:

  1. your route -> localhost:4200/child2.
  2. resolver takes the action.
  3. your route will change to localhost:4200/child2/:postID.

So when your resolver takes the action the route still is localhost:4200/child2 and route.params.postID will return undefined.

You can use Location from @angular/common to replaceState of url and then navigate to child2/:postID. This way you will have id in resolver.

CodePudding user response:

Try accessing through 'paramMap'

@Injectable({ providedIn: 'root' })
export class DemoResolver implements Resolve<any> {
  constructor() {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    console.log(route.paramMap.get('postID')); // try with this code
  }
}

Note: Check if you have registered your resolver in your module as this example:

{
  provide: 'DemoResolver',
  useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => response
}

For more information: https://angular.io/api/router/Resolve

  • Related