0

I want to get some data from the resolver after I do some filtering with the data I get from the backend. Everything works fine with getting the data from the backend and filtering it, but the problem is that I cannot return the final data so I can get it into the component, Please see below my code:

Resolver:

resolve = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> => {
    let routeObjKeys = Object.keys(route.params);
    let jobApplicationsArray = [];
    if(routeObjKeys.length !== 0) {
      let response = this.jobApplicationsService.getJobApplications('', 0, 100, 'firstName', 'ASC').subscribe(data => {
        routeObjKeys.forEach(function(key) {
          jobApplicationsArray.push(data["data"].filter(jobApp => jobApp.id === route.params[key])[0]);
        });
        console.log("jobApplicationsArray: ", jobApplicationsArray);
        return jobApplicationsArray;
      });
      return Observable.of(response);
    } else {
      return this.jobApplicationsService.getJobApplications('', 0, 10, 'firstName', 'ASC');
    }

  }

Component:

getResolverData = () => {
    this.route.data.subscribe(data => {  // Get the data from the resolver
        console.log('jobApplications from component: ', data);
      });
  }

Into the resolver, the jobApplicationsArray array contains the filtered data, but in the component it is undefined, so I think I don't return it properly from the resolver. Please advise. Thanks!

decebal
  • 1,151
  • 3
  • 18
  • 38
  • I'd suggest to debug in your resolver. Use console.log() in both of your return cases and check whether you reach one of these points and what the returned value looks like. –  Mar 22 '18 at 17:06

1 Answers1

0

I managed to solve this by using map instead of subscribe, so I returned an Observable instead of a Subscriber:

resolve = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> => {
    let routeObjKeys = Object.keys(route.params);
    let jobApplicationsArray = [];
    if(routeObjKeys.length !== 0) {
      return this.jobApplicationsService.getJobApplications('', 0, 100, 'firstName', 'ASC').map(data => {
        routeObjKeys.forEach(function(key) {
          jobApplicationsArray.push(data["data"].filter(jobApp => jobApp.id === route.params[key])[0]);
        });
        return jobApplicationsArray;
      });
    } else {
      return this.jobApplicationsService.getJobApplications('', 0, 10, 'firstName', 'ASC');
    }
  }
decebal
  • 1,151
  • 3
  • 18
  • 38