【问题标题】:Getting the data from the resolver in Angular从 Angular 中的解析器获取数据
【发布时间】:2018-09-01 04:48:03
【问题描述】:

在对从后端获取的数据进行过滤后,我想从解析器获取一些数据。从后端获取数据并对其进行过滤一切正常,但问题是我无法返回最终数据,因此我可以将其放入组件中,请参阅下面的代码:

解析器:

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 数组包含过滤后的数据,但在组件中它是未定义的,所以我认为我没有从解析器正确返回它。请指教。谢谢!

【问题讨论】:

  • 我建议在您的解析器中进行调试。在您的两种退货情况下使用 console.log() 并检查您是否达到这些点之一以及返回的值是什么样的。

标签: angular rxjs resolver


【解决方案1】:

我设法通过使用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');
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多