angularangular-resolver

Angular 6+ resolver doesn't load video url


I am trying to load a video url after the data be loaded from the server. I am using a resolver but it doesn't work because the video is loaded before the data some times. What I am doing wrong?

component.ts

this.valuePairService.getName('myVideoUrl').then(
  (responseUrl: any) => {
    this.videoUrl =
      responseUrl.value === undefined && this.hasVideo
      ? '//player.vimeo.com/video/09452678?dnt=1' 
        : responseUrl.value;
  }
);

resolver

@Injectable({ providedIn: 'root' })
export class ValuePairServiceResolver implements Resolve<string> {
    constructor(private nameValuePairService: valuePairService) { }

    resolve(route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ): Observable<any> | Promise<any> | any {
        return this.valuePairService.getName('myVideoUrl');
    }
}

routing module

  {
    path: 'videos',
    resolve: { ValuePairServiceResolver },
    component: VideosComponent
  },

Solution

  • Your syntax in the routing module is incorrect. You need to specify the property name which will contain the resolved value:

    resolve: { videoUrl: ValuePairServiceResolver }

    Also, you're not using it correctly in the component. You should inject ActivatedRoute to the constructor and then you'll be able to access the resolved data:

    constructor(private route: ActivatedRoute) { }
    
    ngOnInit() {
      this.route.data.subscribe(({ videoUrl }) => {
        // you can access videoUrl here
      });
    }