Using Angular 2 to create an Observable type that mediates two separate http.get calls

In my ng2 service, I have a method that contains two http.get calls. Here is an example of the function:

getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }

The issue arises when trying to subscribe to this function in my component because it is not of type Observable<Example>.

When attempting to replace the 'any' type with Observable<Example>, I encounter the error:

A function must return a value as its declared type is neither 'void' nor 'any'

However, I do return a value after receiving the response.

Is there a way to solve this problem without creating two separate functions?

Although I did review this answer:

Answer №1

Consider implementing the following code snippet within your method body. Although this is one approach, there are alternative solutions available.

return this.http
   .get(apiUrl, options)
   .map(response => response.json())
   .flatMap(example => {
       this.example.FirstName = example.FirstName;
       this.example.LastName = example.LastName;

       return this.http
           .get(`/api/${userId}`)
           .map(response =>  {
               let example =response.json();
               this.example.Street = example.Street;
               this.example.City = example.City;

               return this.example;
           });
   });

Answer №2

Here is a solution that utilizes the flatMap operator from rxjs/Rx :

import {Observable} from 'rxjs/Rx';

ngOnInit() {
  const usersId = ['USR002', 'USR004'];
  this.makeRequest(usersId);
}

makeRequest(queryArray, prevObservable = null) {
        if (queryArray.length) {
            const url = 'api/' + queryArray.shift();
            let observable = null;
            if (prevObservable) {
                observable = prevObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.makeRequest(queryArray, observable);
        } else {
            return prevObservable;
        }
    }

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

The Angular Animation feature seems to function properly only upon the initial click

Why does the animation (translateX) only work on the first click in the stackblitz example provided? How can I make it work every time? Thanks for any help! https://stackblitz.com/edit/angular-ivy-p9strz ...

During the rendering process, the property "quote" was accessed, however, it is not defined on the current instance. (Vue.js)

Every time I try to retrieve data from the kanye API, I encounter this error message: Property "quote" was accessed during render but is not defined on instance. Below is the code snippet that triggered the error: <template> <div> ...

What is the best way to transfer data to a component that is not directly related

I am looking to showcase an image, title, and description for a specific recipe that I select. Here is my setup using ItemSwiper (parent): <template> <Slide v-for="recipe in storeRecipe.data" :key="recipe.rec ...

Despite the presence of ngIf, the tab is still displayed

Even though ngIf is used, the FirstTab remains visible. How can I completely remove the tab? Here is the code snippet: <tabs style="min-height:auto"> <tab tabTitle="FirstTab" *ngIf="str=='dp'" > <first-tab> ...

Listener document.addEventListener (function() {perform the function as shown in the illustration})

Currently facing an issue that I'm struggling to resolve, attempting to execute a code snippet from the ngcordova website without success. While using the plugin $cordovaInAppBrowser.open ({... it generally functions well until the inclusion of the ...

I am having trouble with my jQuery wrap function and it is not functioning correctly

I'm having trouble with implementing the jQuery wrap function. (function ($) { $.fn.customWrap = function () { applyWrapper(this); return this; }; function applyWrapper($element) { var $input = $('<input&g ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

I am currently working on building a single-page application using React and Vite. However, I am facing an issue where the page is not rendering anything and just displaying a blank screen. Can anyone provide guidance on troubleshooting and

I am currently facing an issue while trying to build a react website using Vite. No matter what I do, nothing seems to render on the page. I even tried removing the react-router-dom and directly rendering the Home file, but still no luck. It appears that i ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

The loading sequence of Vuetify CSS for buttons is inconsistent in the production build, leading to functionality problems

I am currently working on a Vue application that utilizes a Vuetify "bottom navigation" component as shown below: <v-bottom-navigation app fixed grow color="#121212" class="bottom-navigation" > <v-btn text tile v-for="menuI ...

Use Jquery to insert HTML content after every third iteration of a for loop

I am endeavoring to display a <div class="clear"></div> after every third iteration of a for loop in a jQuery context. In PHP, this can easily be achieved using if($i%3 == 0), but how does one go about implementing this in jQuery or JavaScript? ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Display the initial JSON data object without the need to choose a link with the help of AngularJS

I have successfully built a webpage that displays JSON data based on the selected link. However, I am facing an issue where I need to show the first JSON data object before selecting any link (initially). Check out the Plunker demo here: http://embed.plnk ...

jQuery function for shuffling the order of a random div?

Upon loading the page, I have implemented a code that randomizes the order of the child divs. Here is the code snippet: function reorder() { var grp = $("#team-posts").children(); var cnt = grp.length; var temp, x; for (var i = 0; i < cnt; ...

A guide to creating test cases for conditional statements in Angular using Jasmine

I am currently working on creating test cases for a custom directive in Angular. I have shared my code on StackBlitz. I would appreciate any guidance on how to address the highlighted if else statements below: if (trimmedValue.length > 14) { // Loo ...

Updating state using props from Relay QueryRenderer

My React component includes a form for updating database records using the React-Relay QueryRenderer component like this: class Update extends Component { //constructor.. //some stuff render() { return( <QueryRenderer environ ...

Navigating within fixed-positioned divs

I'm attempting to create something similar to the layout seen on: The desired effect is to have fixed content on the right side, with only the left side scrolling up to a certain point before the entire page scrolls normally. However, in my implement ...

Should I write out the typescript .d.ts file by hand or generate it automatically

When using Typescript, you can utilize the "declaration": true" option in tsconfig to automatically generate d.ts files from your existing Typescript code. Although they may not be as concise as manually written ones, I am curious if there is any downside ...

"Seeking assistance with concept sharing and content transmission. In need of guidance

Basic Question I'm stuck trying to brainstorm a concept to reach my objective. I am having trouble figuring out how to navigate the DOM correctly with my chosen method. The Objective First, let me explain what I am doing: I use ajax to bring HTML ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...