Leveraging JSON data in subsequent GET request in Ionic 3

My application receives input, concatenates it to a string, and then requests JSON data. The response includes the following first two lines: https://i.sstatic.net/h6YNH.png

Now, I need to update my code to be asynchronous. It should make the initial call, wait for a response, retrieve the "id", store it in a variable, and use it in a second call. However, my current code is not functioning as expected. It's failing to retrieve the id because it is not truly asynchronous.

  grabRAW(email){
    this.grabID(email).subscribe(data => {
      this.idList = data.data;
    });
    let id = this.idList[0].id;
    return this.http.get(((this.url1.concat(id))).concat(this.url2))
      .map((res: Response) => res.json())
      .do((res:Response) => console.log(res))
  }
  grabID(email){
    return  this.http.get(this.url.concat(email))
      .map((res: Response) => res.json())
      .do((res:Response) => console.log(res))
  }

The 'url' is concatenated with the email provided as input in the first call, and the id obtained from the first call should be concatenated between url1 and url2 for the second call. The goal is to consolidate everything into one function and ensure that the response of the second call is mapped and returned eventually.

EDIT: Here is the TypeScript function on the page that calls this service provider:

grabInfo(){
    loader.present();
    this.ServiceProvider.grabRAW(this.email).subscribe(data => {
        this.infoList = data.data;
        if (typeof this.infoList[0] != 'undefined'){
          loader.dismiss();
          this.navCtrl.push(ResultPage,{infoList: this.infoList})}
        else{
          loader.dismiss();
          let alert = this.toastCtrl.create({
            message: "No Data found for this Email Address",
            duration: 4000,
            position: 'bottom'
          });
          alert.present();
        }
      }
    );
  }

Answer №1

To enhance the efficiency of your code, consider implementing switchMap instead of subscribing to the first observable:

import { Observable } from 'rxjs/Observable';
import { switchMap }  from 'rxjs/add/operator/switchMap';

// ...

fetchData(email): Observable<any> {
    return this.fetchID(email)
               .switchMap(data => {
                   this.IDs = data.data;
                   let id = this.IDs[0].id;

                   // Proceed with the second http request
                   return this.http.get(((this.url1.concat(id))).concat(this.url2))
                              .map((res: Response) => res.json())
                              .do((res:Response) => console.log(res))
        });
}

fetchID(email): Observable<any> {
    return this.http.get(this.url.concat(email))
        .map((res: Response) => res.json())
        .do((res:Response) >> console.log(res))
}

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

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

Guide to executing a batch file using electron

I've been struggling all morning to find a solution. I've gone through several tutorials, but I still can't wrap my head around how this should work. In my Electron app, there is a button that, when clicked, should execute a batch file (hpm ...

What is the best way to transform a current callback API into promises?

Exploring the transition to working with promises poses a challenge when dealing with callback APIs structured as follows: ###1. Handling DOM load or other one-time event: window.onload; // set to callback ... window.onload = function() { }; ###2. Utili ...

Localhost Firebase authentication with Facebook integration

I am currently working on a Vue.js app that integrates Firebase for authentication, specifically with the Facebook provider. Despite configuring my Firebase code correctly, I continue to encounter the "Can't load URL: The domain of this URL isn't ...

Retrieve and process information retrieved from an Ajax call in ASP.NET using AJAX

When I receive a list of data from an Ajax call, it looks like this. $(document).ready(function () { var hashtag = 'dilwale' var accessToken = '16741082.1b07669.121a338d0cbe4ff6a5e04543158a4f82' $.ajax({ url: ' ...

Problem with fetching Grails

I have a table nested within an anchor tag. The table is centered on the page, with each row containing an image. When the page loads, I noticed the following: a) The table initially appears at the top-left corner of the screen. b) As there are multiple v ...

Using RadSideDrawer with Typescript in Vue class components: A Step-by-Step Guide

I am attempting to integrate external components into Vue Typescript Class Components. Following the installation of the standard template, I made modifications to its <script> block based on this guide: import { Vue, Component, Prop } from "vue-pro ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

"The JavaScript code that functions perfectly in the browser console, but fails to execute when running in the actual

I'm encountering an issue with a simple piece of JavaScript code that seems to only work when executed in the browser console: <script> $(".hopscotch-close").click(function () { alert("Hi"); Cookies.set("tourState", "closed" ...

Error encountered with structured array of objects in React Typescript

What is the reason for typescript warning me about this specific line of code? <TimeSlots hours={[{ dayIndex: 1, day: 'monday', }]}/> Can you please explain how I can define a type in JSX? ...

Enhancing web page interactivity through dynamic element names with Javascript and jQuery

I have an interesting HTML setup that looks like this: <div> <input type="text" name="array[a][b][0][foo]" /> <input type="text" name="array[a][b][0][bar]" /> <select name="array[0][a][b][baz]>...</select> </div> ...

Which design pattern would be best suited for monitoring the completion of multiple ajax requests?

In my code, I have combined 3 separate ajax calls in one function along with checkAjaxCompletion method to monitor each ajax completion flag. The current approach involves sending multiple independent ajax calls and using an interval method to continuousl ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

Is there a way to conceal the contents of a page until all the images have finished loading?

I'm currently working on improving the performance of a website that is loading very slowly. I have already reorganized, compressed and minified the JavaScript and CSS files, but the main issue seems to be with the images. The site contains large imag ...

Is there a way to determine whether a mouse-down event took place on the scroll-bar or elsewhere within the element?

Looking for a solution with my HTML div acting as a canvas containing various objects. The issue lies in the fact that when attempting to draw a selection rectangle by dragging with the mouse, if scroll bars appear due to the large size of the canvas, scr ...

The JQuery function .remove() will not properly remove dynamically added elements

I am facing an issue when trying to remove an element from a page. Every time I click on a button on the page, it adds a div with the following structure: <div class="holder-div" style="position: relative;display: inline-block;"> ...

Having difficulty installing TypeScript on my machine

https://i.stack.imgur.com/l6COf.pngHaving trouble installing TypeScript with the following error: npm WARN registry Using outdated package data from https://registry.npmjs.org/ due to an error during revalidation. npm ERR! code E500 npm ERR! 500 Interna ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...