Error in Angular 8 Pipe: Variable remains undefined outside of Subscription

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

What I attempted

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

In the example above, the newValue variable is undefined. How can one retrieve it to return the new value for the pipe outside of the Subscription block?

Answer №1

Getting asynchronous data synchronously may not work as expected.

To achieve this, you should return an Observable value in your pipe and modify the data within the map operator of RxJS, rather than in the subscribe method.

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

When using this pipe in the template, make sure to connect it with the AsyncPipe.

For example: data | yourPipe | async

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

When launched from a push notification, the application closes upon pressing the system's back button

There seems to be an issue with the title, as it only occurs if I click anywhere on the screen beforehand. It appears that the application is not active before the click, causing the registered back button action to not work. The code for the action is as ...

Having trouble reading local storage in Angular 2

I have inserted a token into local storage and am attempting to console.log it. Here is my code snippet: ngOnInit(){ console.log('Member Info: ', JSON.parse(localStorage.getItem('LOCAL_TOKEN_KEY'))); } Although this seems correct ...

Receive notification indicating that the function is of void type

As a newcomer to angular, I am currently in the process of setting up my authorization module for an ionic project I am developing. I have made significant progress, but I have encountered an issue with the 'auth' service that I created. Within ...

What's the deal with the `return of ()` syntax?

Just came across this piece of code: https://i.sstatic.net/JZXP5.png Code snippet in typescript. The first line looks like: ... return of (true); Can someone explain this syntax to me? ...

How to test Angular HttpClient in protractor end-to-end testing

Upon loading my application, an http call is made to the backend which causes my e2e test to fail in CI pipelines where no backend is available. I attempted to handle the error using the rxjs catchError operator on the http call. Additionally, I tried wr ...

Unable to import JSON from the Angular library component I am working with

For those willing to assist me, the Github repository for my angular library can be found here: https://github.com/sandrocsimas/ngx-material-palette-picker I am embarking on creating my first Angular library and have utilized Angular CLI commands to gener ...

Unable to Load website with In-App-Browser

Hello there, I'm a newcomer to Ionic and I'm hoping for some guidance. My goal is to convert my website into an app, and after doing some research, it seems that utilizing the in-app-browser is the most suitable approach. constructor(public navC ...

Guide on: Reloading an AngularJS Route

I'm in the process of setting up a Typescript SPA project using Visual Studio and AngularJS for routing. Here is my current configuration... var app = angular.module("myApp", ["ngRoute"]); app.config(($routeProvider, $locationProvider) => { $route ...

Tips for implementing index values in typescript within an Angular Material Table

<mat-cell *matCellDef="let element; let i index">{{ element.patientName }}<input type="hidden" [(ngModel)]="index" value={{i}}/></mat-cell> I created an index variable to access the value in the typescript f ...

When a webpage reload triggers a 404 error, my website's iframe with the source "videoUrl | sanitize" will display

I am attempting to retrieve a videoUrl from a database and set it to the iframe [attr.src] in order to display a YouTube video. It is imperative that the data originates from the database, as there are limitations preventing us from directly uploading and ...

When working with Typescript and Vue.js, it's important to ensure that properties are initialized before

Check out the following code snippet: export default class PrimitiveLink extends Vue { style = { // Reset display: 'inline-block', textDecoration: 'none', outline: 'none', // Theme ...this.themeStyle ...

Attempting to integrate Bootstrap 5 accordion into Angular 17 using ngFor has posed a challenge for me

<div class="accordion w-50 mx-auto" id="accordionExample"> <div *ngFor="let note of notes; index as i;"> <div class="accordion-item"> <h2 class="accordion-header" id="headi ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

What steps do I need to take to update my mat-slide-toggle to align with the latest design standards in Angular 18

My application is built with Angular 18 (18.1.2) and Material (18.1.2). I have encountered an unusual issue where my mat-slide-toggle appears completely unstyled, lacking the theme colors and resembling a slide-toggle from an older version of Angular. The ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Utilizing TypeScript to perform typing operations on subsets of unions

A TypeScript library is being developed by me for algebraic data types (or other names they may go by), and I am facing challenges with the more complex typing aspects. The functionality of the algebraic data types is as follows: // Creating ADT instatiat ...

Incorporating real-time checked checkbox values into a running list

When displaying a list of preferences as checkboxes, I encountered an issue with the binding part. I am trying to capture the IDs of the checkboxes that are checked. Here is my attempt, which unfortunately does not work: <div class="checkbox" *ngFor="l ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...