The successful completion of an Angular2 HTTP request relies on the data obtained from a previous response

I developed a service that performs various http calls with different parameters. quote.service.ts

getQuotes(){
    let params = {
        "Type": "BasicDetail",
    }
    return this.http.post(this.url,params)
    .map(res => res.json())
}  

getOptions(){
    let params = {
        "Type": "Hoteloption",
    }
    return this.http.post(this.url,params)
    .map(res=>res.json())
}

getServiceWiseOptions(){
    let params = {
        "Type": "ServiceWiseOption",
    }
    return this.http.post(this.url,params)
    .map(res => res.json())
}

In my component code, I invoke the getOption() within the constructor.

component.ts

getOption() {
 this.quoteService.getQuotes().mergeMap( quotes => {
  if(this.quotes.BasicDetails[0].QuotType == 'QUOTTYP-3'){
    return this.quoteService.getServiceWiseOptions()
  }
  else{
    return this.quoteService.getOptions()
  }
})
 .subscribe(
  options => {
    this.optionsdata = options.resultData;             
    if(this.quotes.BasicDetails[0].QuotType == 'QUOTTYP-3'){
      this.servicewiseData = options.resultData.ServiceWiseOption;
    }else{                
      this.servicewiseData = options.resultData.Hoteloption; 
    }    
  },
  )
}

The requirement is to call either getServiceWiseOptions() or getOptions() from the service based on the response of getOption(). If the QuotType: matches, then call getServiceWiseOptions(); otherwise, call getOptions().

Although the function getOption() works sometimes, it fails to call either of these functions at times.

I need suggestions on what steps to take next. I suspect it might be an issue with the mergeMap().

Answer №1

When writing your getOption() function, be careful to reference the response data correctly by using this, as it will create a controller variable instead of accessing the actual response data,

Make sure to update this.quotes to just quotes

getOption() {
 quotesService.getQuotes().mergeMap( quotes => {
    quotes = quotes; // this line if you want it to use anywhere else
  if(quotes.BasicDetails[0].QuotType == 'QUOTTYP-3'){
    return quoteService.getServiceWiseOptions()
  }
  else{
    return quoteService.getOptions()
  }
})
 .subscribe(
  options => {
    optionsdata = options.resultData;             
    if(quotes.BasicDetails[0].QuotType == 'QUOTTYP-3'){
      servicewiseData = options.resultData.ServiceWiseOption;
    }else{                
      servicewiseData = options.resultData.Hoteloption; 
    }    
  },
  )
}

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

By default, the ng build command constructs the development environment rather than the production environment

Whenever I execute the "ng build" command in the terminal, it constructs the development environment instead of the production environment. If I use the "ng build --prod" command, everything works as expected. However, by default, it continues to build th ...

The type declaration for the Storage.prototype.setObject method

I'm facing a challenge in creating a d.ts file for the given DOM feature. Storage.prototype.setObject = function(key:string, value:any) { this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key:string) { var va ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

Generate an object in Typescript that includes a dynamic property calculated from an input parameter

Is there a way to achieve the following function in TypeScript? function f<T extends 'a' | 'b'>(t : T): {[t]: ...} { return {[t]: ...} } This code is intended to make f('a') have type {'a': ...} and similarl ...

Custom JSX element failing to include children during addition

I have created a unique component in JSX, like this: const CustomComponent = ({content}) => { return <div className={content}></div>; } I am using it as follows: <CustomComponent content={"xyz"}> <p>Some additio ...

What is the best way to access a property within a typescript object?

I'm working with the following code snippet: handleSubmit() { let search = new ProductSearch(); search = this.profileForm.value; console.log(search); console.log(search.code); } When I run the console.log(search) line, it outputs: ...

Angularfire/Firebase utilizes the Authorization Code Grant flow for OAuth

I am trying to understand the authentication flow used by applications that depend on Firebase for single sign-on authentication. While I know that most SPA and client applications use the "implicit flow" due to everything happening in the browser without ...

There was a parsing error due to encountering an unexpected reserved word 'interface' in the code, as flagged

I'm encountering an issue with my code when trying to utilize Props. The error message I'm receiving is "Parsing error: Unexpected reserved word 'interface'. (3:0)eslint". This project is being developed using next with TypeScript. Er ...

HTML/Angular tutorial: Sharing an On-Click value with a different HTML element within the same component

As a newcomer to this, I could really use some guidance. Currently, I have a Mat Table that is displaying a specific range of data from my firestore. My goal is to be able to click on a particular row and have its data appear in a list below the table. I ...

Fix the TypeScript issue encountered during a CDK upgrade process

After upgrading to version 2.0 of CDK and running npm install, I encountered an issue with the code line Name: 'application-name'. const nonplclAppNames = configs['nonplclAppNames'].split(','); let nonplclAppNamesMatchingState ...

Ways to change the CSS styling of the placeholder attribute within a textarea or input field tag

I am currently working on adjusting the font size of the text within the placeholder attribute of a textarea element. While I have been successful in achieving this using vanilla CSS, I have encountered difficulties when trying to implement the same concep ...

Encountering CORS issue while attempting to update information in Angular 9

Whenever I try to use the header in the following manner, everything works fine. However, I encounter a CORS error when attempting to use the put method. Despite multiple attempts, manually hard-coding the body did not resolve the issue and the CORS error ...

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Guidelines for converting an array into checkboxes using React Native with TypeScript

As I embark on my React Native journey, I have chosen to use TypeScript in my project. Currently, I am faced with the challenge of mapping an array into a checkbox. Enclosed below is a snippet from my JSON file: { "stud_name": "Adam", "sex": "male" ...