代码之家  ›  专栏  ›  技术社区  ›  Vueer

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

  •  0
  • Vueer  · 技术社区  · 5 年前

    我试过的

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

    1 回复  |  直到 5 年前
        1
  •  1
  •   Kamil Augustyniak    5 年前

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

    在您的管道中,您应该返回可观察的值。在这种情况下,您可以在 map Rxjs运算符,不在subscribe中。

    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