Search code examples
angulartypescriptsubscription

Angular 8 Pipe - Variable is undefined outside Subscription


How can I access a variable inside a subscription in an angular pipe to return the transformed value?

What I tried

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

the newValue variable is undefined in this example. How could I retrieve them to return the new value for the pipe outside this Subscription?


Solution

  • You want to get asynchronously data as synchronously. It doesn't work that.

    In your pipe, you should return Observable value. In this case, you modify your data in map Rxjs operator, not in 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;
      }));
    }
    

    And when you want to use this pipe in the template you have to connect it with AsyncPipe

    For example: data | yourPipe | async