从Angular中的解析器获取数据

时间:2018-03-22 16:33:03

标签: angular rxjs 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');
    }

  }

组件:

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

在解析器中,jobApplicationsArray数组包含已过滤的数据,但在组件中它未定义,所以我想我不能从解析器中正确返回它。请指教。谢谢!

1 个答案:

答案 0 :(得分:0)

我设法使用map而不是subscribe来解决这个问题,所以我返回了一个Observable而不是订阅者:

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');
    }
  }