Support different response types when making nested API calls

When working with two API calls that return different responses, one typed as TestData1Res and the other as TestData2Res, how can I handle the scenario where the response could be either type and process the property?

`TestData1Res{ testData: string }

TestData2Res{ data: string }

this.getData1().pipe(catchError(error => this.getData2()))
  .subscribe(
    (res: TestData1Res|TestData2Res) => {
      if (res.testData) { //error 'Property 'testData' does not exist on type 'TestData1Res | TestData2Res'
      }
      if (res.data) { //error 'Property 'data' does not exist on type 'TestData1Res | TestData2Res'
      }
    }
  );`

Answer №1

Utilizing dynamic data type could prove beneficial

    Implementing dynamic data types in this scenario may yield positive results:
    
    this.getData1().pipe(catchError(error => this.getData2()))
  .subscribe(
    (res: any) => {
      if (res["testData"]) { 
        // Execute code block
      }
      if (res["data"]) { 
        // Execute code block
      }
    }
  );

Answer №2

When you need to make consecutive API calls, one after the other:

this.getData1().subscribe(data => {
    // Successfully received data from getData1
    this.getData2().subscribe(data => {
        // Successfully received data from getData2
    }, err => {
        // Error with getData2
    }) 
}, err => {
    // Error with getData1
})

If you want to make both API calls simultaneously, you can utilize forkjoin from rxjs:

forkjoin([this.getData1(), this.getData2()]).subscribe(result => {
    // result[0] - Result of getData1
    // result[1] - Result of getData2
}, err => {
    // Handle error if something goes wrong
})

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

Displaying or concealing list elements in Angular 6

I am working on a simple Angular app that displays a list of items. I want the behavior to be such that when the first item in the list is clicked, its description (card) should be displayed. And, if the second item is clicked and its description is displa ...

Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet: export function buildRoutes(options: any, router: Router, roles: string[]): Routes { const lazyRoutes: Routes = Object.keys(options) ...

The Vercel public domain is not functioning as expected

After successfully developing a next.js application with user auth using NextAuth and deploying it to Vercel, I encountered an issue related to the notifications page functionality. The problem arises when the app checks for an active session; if none is f ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

A guide on showcasing real-time data with Angular's service feature

home.component.ts <h1>{{ (reportsToday$ | async)}}</h1> <div echarts [options]="alertsDaily$ | async"> <div echarts [options]="alertsToday$ | async"> <div [onDisplay]="alertsDaily$ | async"> report.component.ts constructor( ...

Transforming a React component into a TypeScript Element results in an automatic 'any' type assignment due to the inability to index an expression of type 'string | number'

I am currently in the process of migrating a React component to TypeScript, but I have encountered an issue that I am struggling to resolve. I am consistently receiving an error related to accessing variantStyles[variant][color], and I cannot pinpoint the ...

What is the method for enabling imports from .ts files without file extensions?

While trying to open a Svelte project with TypeScript, I encountered an issue where all imports from .ts files were showing "Cannot resolve symbol" errors. https://i.stack.imgur.com/FCVxX.png The errors disappear when the .ts extension is added to the im ...

Guide on subscribing to an object from a service in Angular 2/5

I am facing an issue where I need to update my property component with data received from the server. In the Service, I have implemented something like this: private events: Event[] = []; eventChanged = new Subject<any>(); // Edit: added an observa ...

Step-by-step guide on defining a context variable within a template

I am looking for a way to make my page dependent on a single model object emitted from an Observable. If it was a list, I would use <div ngFor="let currentListItem of myObservable | async" > However, since I only have one model and not a list, ngFo ...

Is it worth incorporating dependency injection for injecting classes?

In the AngularJS days, factory was commonly used to inject classes instead of instances. This practice continues in Angular 2: {provide: MyClass, useFactory: () => { return MyClass }} ... constructor(MyClass) { let instance = new MyClass(); } Howe ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

Can a type be referenced using the generic name?

My selection includes: export type DocumentType = | Item | List | User export type DocumentInputType = | ItemInputType | ListInputType | UserInputType I want to develop a feature that can determine the input type based on the document type wi ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

Utilizing the [innerHTML] attribute within the <mat-select><mat-option> tags

I have integrated the use of [innerHTML] within <mat-option> in <mat-select>, which displays correctly in the drop-down list but not for the selected value. Versions: Browser Google Chrome 68.0.3440.106 (Official Build) (64-bit) Angular 6.1 ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Attempting to integrate WebdriverIO into an Angular Electron application

Context: Currently, I am in the process of implementing the fundamental WebdriverIO example within an Angular Electron App. My application is built on the foundation of the Angular Electron Boilerplate. To set up, I have installed webdriverio and @types/we ...

Using setTimeout() and clearTimeout() alongside Promises in TypeScript with strict mode and all annotations included

Many examples of timer implementations using Promises in JavaScript seem overly complex to me. I believe a simpler approach could be taken. However, I am looking for a solution specifically tailored for TypeScript with the "strict": true setting and all ne ...

The argument type 'MatSort | null' cannot be assigned to the parameter type 'MatSort' in this scenario

When attempting to retrieve sorted data from MatTableDataSource, I used the following code: this.source = this.dataSource.sortData(this.dataSource.filteredData,this.dataSource.sort); Unfortunately, I encountered an error message: Argument of type ' ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Discovering the optimal method for modifying the state of an object within Object-Oriented Programming using Typescript

I have implemented Object Oriented Programming in my project and I am exploring ways to effectively change the state of an object while ensuring its integrity. Although I have created a code snippet for this purpose, I am curious if there are more optimize ...