What is the best way to extract a variable value from the subscribe method and make it available for use in an Angular 10 service method's return statement using TypeScript?

 getProductbyFilter(filter: filterDataModel): Observable<any> {
  this.stringtoArrayService.convertStringtoArray(some string input).subscribe(productUserResponse => {
  if (productUserResponse) {
    this.userProfileProduct = productUserResponse;
    this.newParams = this.userProfileProduct[0].Function_Network;
    if (this.newParams != null) {
      this.updatedStr = this.newParams.replace('&', '__', this.newParams);
    } else {
      this.updatedStr = this.userProfileProduct[0].Function_Network;
    }
  }
});
  return this.http.post(url + this.updatedStr, filter, httpOptions);}

I have explored various resources which suggest using a method inside subscribe. However, I am encountering an issue where I am unable to access the value of this.updatedStr as it returns undefined. Is there any solution to this problem? Please assist.

  1. assigning variable outside subscribe

  2. how-to-get-value-outside-typescript-subscribe-function

Answer №1

Give this a try, although please note that it hasn't been verified.

updateStringFromResponse(userResponse){
  if (userResponse) {
    this.userProfileProduct = userResponse;
    this.newParams = this.userProfileProduct[0].Function_Network;
    if (this.newParams != null) {
      this.updatedStr = this.newParams.replace('&', '__', this.newParams);
    } else {
      this.updatedStr = this.userProfileProduct[0].Function_Network;
    }
  }
}

fetchProductWithFilter(filter: filterDataModel): Observable<any> {
 return this.stringtoArrayService.convertStringtoArray(some string input).pipe(
  tap(userResponse => this.updateStringFromResponse(userResponse)),
  switchMap(_=>performActionAfterUpdateStr(filter))
);

performActionAfterUpdateStr(filter: filterDataModel): Observable<any>{
  // set httpOptions and url
  return this.http.post(url + this.updatedStr, filter, httpOptions);
}

Answer №2

That's the inner workings of JavaScript

fetchProductByFilter() {
  executeSubscriptionToUpdateString();
  return fetchHttpCallObservable();
}

executeSubscriptionToUpdateString
operates independently from fetchHttpCallObservable. This ensures that JavaScript completes fetchHttpCallObservable before
executeSubscriptionToUpdateString

This results in this.updatedStr being undefined because it returns before receiving a value from

executeSubscriptionToUpdateString
.

Implement Promise or Async/Await to make fetchHttpCallObservable wait for

executeSubscriptionToUpdateString
to finish processing.

This way, you can successfully return from the initial method;

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

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

Working with an array of objects with varying shapes and validating them

I have dedicated quite a bit of time to this task and would greatly appreciate some assistance. I am in need of a component (a function) that can accept an array of objects while also validating the properties of these objects. Here are the interfaces and ...

Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object: { id: 14070 project: {id: 87, name: "Test project for time tracking"} issue: {id: 10940} user: {id ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

When configuring the Redux logger, the type 'Middleware<{}, any, Dispatch<UnknownAction>>' is not compatible with type 'Middleware<{}, any, Dispatch<AnyAction>>'

In my React project, I have defined the redux logger with the package version "redux-logger": "^3.0.6" in the file store.ts as shown below: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/re ...

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

Building an Angular CLI application with Typescript that handles multiple HTTP calls using polling through a timer

I am working with a Django backend and I need to check the status of multiple Celery Tasks () every 3 seconds. For instance, let's say I have 4 task IDs: 3099023 3493494 4309349 5498458 My goal is to make an http.get<...>(backend) call every ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Mapping a Tuple to a different Tuple type in Typescript 3.0: Step-by-step guide

I am working with a tuple of Maybe types: class Maybe<T>{ } type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>]; and my goal is to convert this into a tuple of actual types: type TupleIWant = [string, number, boolea ...

I am looking to personalize the AddedToCartDialogComponent with the selector cx-added-to-cart-dialog

I've been trying to tailor the AddedToCartDialogComponent by incorporating new elements into the dialog window. Despite closely following Spartacus documentation, I am unable to see any changes taking effect. Running on Spartacus version 4, here is a ...

The Type {children: Element; } is distinct and does not share any properties with type IntrinsicAttributes

I am encountering an issue in my React application where I am unable to nest components within other components. The error is occurring in both the Header component and the Search component. Specifically, I am receiving the following error in the Header co ...

How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI. This is my Service: fetchPdfDocument(): Observable<any> { return this.httpClient .get(this.configuration.serverUrl + this.configuration.getPdfDoc, { re ...

Can a TypeScript generic version of the Y-combinator be successfully executed?

Here is an interesting JavaScript implementation of the Y-combinator: const Y = g => (x => g(x(x)))(x => g(x(x))) //or const Y = f => { const g = x => f(x(x)) return g(g) } I've been thinking, could it be possible to create a TypeS ...

How to upgrade Angular Header/Http/RequestOptions from deprecated in Angular 6.0 to Angular 8.0?

When working on http requests in Angular 6.0, I typically follow this block of code. I attempted to incorporate the newer features introduced in Angular 8.0 such as HttpClient, HttpResponse, and HttpHeaders. However, I found that the syntax did not align ...

The information from the data source is not getting filled in

I recently started working with Angular (Version 14.2.10) and I am trying to make a REST call to populate data in the UI. However, only the header is displayed without any data showing up. I suspect there is a minor issue that I can't seem to pinpoint ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...

Set up SystemJS to properly load my Angular 2 component module

Recently, I made the switch from ng1 to ng2. I successfully imported Angular 2 and its modules into my project: <script src="/node_modules/systemjs/dist/system.src.js"></script> <script src="/node_modules/rxjs/bundles/Rx.js"></script& ...

Having trouble accessing input value when using FormArrayName with FormBuilder?

When attempting to retrieve the value from the input field using formArrayName, I am encountering an issue where it returns null instead. The console shows that I can get the value for client name but not for secrets. What I need is for the returned value ...

Angular 2's latest release, RC.5, introduces an indispensable singleton global shared

I am currently working on implementing global singleton services. I came across this solution - https://angular.io/docs/ts/latest/guide/ngmodule.html#!#shared-module, but unfortunately it is not working for me. Here's a simplified version of my share ...