Angular 8 管道 - 变量在订阅外未定义

Angular 8 Pipe - Variable is undefined outside Subscription

如何在 angular 管道中访问订阅内的变量到 return 转换后的值?

我试过的

transform(value: any, ...args: any[]): any {

  const clientKey = args[0];
  let arr = [];
  let newValue;


  this.dbJobs.getJobsFromKey(clientKey).pipe(take(1)).subscribe(jobs => {
    if (jobs && jobs.length) {

      jobs.forEach((job) => {
        arr.push(job.time);
      });
    }
    newValue = arr.reduce((a, b) => {
      return a + b;
    }, 0);

    return newValue;
  });

  return newValue;
}

newValue 变量在此示例中未定义。我如何才能将它们检索到 return 此订阅外部管道的新值?

您想以同步方式获取异步数据。那样不行。

在您的管道中,您应该 return 可观察值。在这种情况下,您在 map Rxjs 运算符中修改数据,而不是在订阅中。

transform(value: any, ...args: any[]): any {

  const clientKey = args[0];
  let arr = [];
  let newValue;


  return this.dbJobs.getJobsFromKey(clientKey)
    .pipe(
      take(1),
      map(jobs => {
    if (jobs && jobs.length) {

      jobs.forEach((job) => {
        arr.push(job.time);
      });
    }
    newValue = arr.reduce((a, b) => {
      return a + b;
    }, 0);

    return newValue;
  }));
}

当你想在模板中使用这个管道时,你必须将它连接到 AsyncPipe

例如:data | yourPipe | async