Angular - The aftermath of subscribing

I have been attempting to use subscribe to return a value to this.voucherDetails, but unfortunately, it doesn't seem to be working as expected.

Below is the code snippet for the getVoucherDetails function which includes the subscribe method.

voucherIDs: string[];
voucherDetails: Promise<any>[];

this.voucherIDs = ['JV-2005-50','JV-2005-40','JV-2005-30'];
this.voucherDetails = this.voucherIDs
.map(id => this.getVoucherDetails(id));
Promise.all(this.voucherDetails)
      .then(() => this.printService.onDataReady());

Here is the function that uses subscribe to userService to fetch data from the database.

getVoucherDetails(voucherid) {
    var splitvoucher = voucherid.split('-');
    var vouchertype = splitvoucher[0];
    var vouchermy = splitvoucher[1];
    var voucherno = splitvoucher[2];
    var vouchernotopass = vouchermy+"-"+voucherno;

    var voucherdate;
    var enteries;

    this.userService.getVoucher(vouchernotopass,vouchertype).subscribe(
        res => {
          voucherdate = res['voucherdate'];
          enteries = res['enteries'];
          return { "vouchertype":vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "enteries":enteries};   
        }
    );       
}

However, the function currently returns undefined. Through my research, I have learned that you cannot directly return from a .subscribe method. I am still trying to figure out a solution to this issue.

Answer №1

When working asynchronously with Observables, callbacks are essential, similar to Promises. The recommended approach is to return an Observable (or Promise) within your method and allow the caller to subscribe to it:

fetchDetails(voucherid) {
    var splitvoucher = voucherid.split('-');
    var vouchertype = splitvoucher[0];
    var vouchermy = splitvoucher[1];
    var voucherno = splitvoucher[2];
    var vouchernotopass = vouchermy + "-" + voucherno;

    var voucherdate;
    var entries;

    return this.userService.getVoucher(vouchernotopass, vouchertype).pipe(
        map(res => {
            voucherdate = res['voucherdate'];
            entries = res['entries'];
            return {"vouchertype": vouchertype, "vouchernumber": vouchernotopass, "voucherdate": voucherdate, "entries": entries};
        })
    );       
}

Utilize the method as follows:

fetchDetails(id).subscribe(v => {
    console.log(v.vouchertype);
    console.log(v.vouchernumber);
    console.log(v.voucherdate);
});

In your scenario:

combineRequests( // combineRequests waits for Observables to complete and then merges their last emitted values.
    this.voucherIDs.map(id => this.fetchDetails(id) // array of observables
).subscribe(responses => {
    console.log(responses);
    this.allDetails = responses;
});

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

Challenges encountered when setting a value to a custom directive via property binding

I'm working on a question.component.html template where I render different options for a specific question. The goal is to change the background color of an option to yellow if the user selects the correct answer, and to red if they choose incorrectly ...

How come the props aren't being passed from the parent to the child component? (React / TypeScript)

Learning TypeScript for the first time and facing an issue with passing props from parent to child components. The error seems to be related to the type of props, but I'm not sure how to fix it since all types seem correct. Error message: "Property ...

Building a search feature with a customized pipe in Angular

I attempted to create my own custom pipe in Angular 6 for filtering a list of campaigns using a search box. Strangely, I am having trouble getting the filter to work on the campaign list. Below is the code snippet that I have written. This is the implemen ...

Instance of exported class declared in Typescript

Currently, I am in the process of developing my initial declaration file for a foreign library known as react-native-background-timer. Within this library, there exists a default export that I am uncertain about how to declare within the index.d.ts file. ...

The letter 'T' has the flexibility to be assigned with any type, even those that are completely unrelated

Currently, I am developing an endpoint within Next.js. My goal is to strictly enforce the JSON structure returned by API endpoints. It would be very beneficial if I could automatically infer the return type of an endpoint and utilize that information in my ...

Limit the frequency of function calls in Typescript

Update: After some research, I've learned that throttle has the capability to drop excess function invocations, making it unsuitable for my needs. I am still seeking an idiomatic solution to process every item in a queue at an appropriate pace without ...

Immediate update: Receiving a status of 400 "Bad request" when trying to make an HTTPPOST

After tirelessly searching through various online resources like Google and Stack Overflow to troubleshoot my code without success, I find myself resorting to posting a question here. The issue at hand involves two nearly identical functions in my service ...

Refreshing display with information received from web socket in Angular 5

On my page, I am receiving an array of data upon page load and displaying it using the *ngFor directive. Additionally, there is a connection established to a Web Socket to receive updated data, which in this case pertains to a timetable for boat trips. The ...

Tips for retrieving a cropped image with Croppr.js

Currently, I am developing a mobile application using Ionic 3. Within the application, I have integrated the Croppr.js library to enable image cropping before uploading it to the server. However, I am facing an issue where I am unable to retrieve the cropp ...

What is the process for importing types from the `material-ui` library?

I am currently developing a react application using material-ui with typescript. I'm on the lookout for all the type definitions for the material component. Despite attempting to install @types/material-ui, I haven't had much success. Take a look ...

Exploring the power of query parameters in Ionic 4

Currently, I am in the process of transitioning a web-based Ionic 3 project to Ionic 4. Upon scanning a QR code, a page is supposed to open with a URL structure like this: domain.com/qanda/pwa/home?user=simon&skill=ionic&role=Admin&Table=132 ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

How to filter ngFor elements in Angular 2 based on user input?

Is there a method for filtering elements rendered through *ngFor based on real-time user input following each keyup event? ...

Ensure that the function's parameters are entered exclusively through TypeScript interfaces

How can I efficiently organize and maintain the function's arguments below without utilizing Typescript? Can this be achieved using Interfaces? // external file export interface TSomeFunctionArgs { someKey: string // there should also be a type ...

Building a continuous timer loop in Angular using RxJS that adapts to changing durations within an array's objects

I am experimenting with a scenario where I read the data, loop based on the duration. For example, starting with "Adam" first, play Adam for a 15-second timer, then move on to the next beginner "Andy" and play Andy for 15 seconds. Once we reach group "int ...

Using optional chaining on the left side in JavaScript is a convenient feature

Can the optional chaining operator be used on the left side of an assignment (=) in JavaScript? const building = {} building?.floor?.apartment?.number = 3; // Is this functionality supported? ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

Issue with ellipsis not functioning correctly on dynamic placeholders when they are in focus

When I focus on my dynamic placeholder input, the text-overflow: ellipsis property is lost for some reason. However, it is regained when blurred. Can anyone explain why this is happening? If you want to experiment with it, I have set up a stackblitz: htt ...

Adding an external component to an Angular 2 project

I've been facing challenges while trying to import an external component from a URL into a new Angular2 application. The issue I keep encountering is with the typescript failing to compile and run the application smoothly. Here is the specific import ...