首页 > 解决方案 > Angular 8 Pipe - 在订阅之外未定义变量

问题描述

如何访问角管道中订阅内的变量以返回转换后的值?

我试过的

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变量未定义。我如何检索它们以返回此订阅之外管道的新值?

标签: angulartypescriptsubscription

解决方案


您希望以同步方式获取异步数据。这行不通。

在您的管道中,您应该返回 Observable 值。在这种情况下,您在mapRxjs 运算符中修改数据,而不是在订阅中。

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


推荐阅读