Executing a series of API calls using Rxjs in Angular that result in a null response

I encountered a situation where I needed to make sequential API calls using RxJs in Angular. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id from the first API, which may be either null or undefined. My objective is to return of(null) if the id is not available, otherwise return the response. Unfortunately, TypeScript errors have emerged in my current implementation. Below is what I have accomplished thus far:

of(personId).pipe(
  take(1),
  switchMap((personId: string) => {
    return this.personService.getById(personId).pipe(
      concatMap((person: Person) => {
        const classId = person?.class?.id || null;
        let class$ = of(null);

        if (classId) {
          class$ = this.classService.getById(classId); // Will return Observable<Class>
        }

        return combineLatest([of(person), class$])
      })
    )
  }),
  tap(([person, class]) => {
    console.log('Person: ', person);
    console.log('Clas: ', class);
  })
).subscribe()

class$ = this.classService.getById(classId);

Within this line, I am encountering the error 'TS2322: Observable is not assignable to Observable`

Do you have any suggestions on how I can resolve this issue? Additionally, do you believe there are ways in which this code could be improved?

Answer №1

instead of using conditional logic, simply use this code snippet

   let class$= classId ? this.classService.getById(classId) : of(null)

Answer №2

The result of calling this.classService.getById is not the same as what you get from of(null), which is why you can't replace the existing value of class$ with it.

One way to solve this issue is to use a ternary operator to set the value of class$ like this:

const class$ = person?.class?.id ? this.classService.getById(classId) : of(null);

Answer №3

At first glance, the use of of(personId) appears unusual.

Have you considered this alternative approach?

this.personService.getById(personId).pipe(
  concatMap((person: Person) => {
    const class$ = person?.class?.id
      ? this.classService.getById(person?.class?.id)
      : of(null);
    return combineLatest([of(person), class$]);
  })
).subscribe(/*...*/);

The error message

TS2322: Observable is not assignable to Observable
seems pretty self-explanatory.

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 could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

Encountered an error when attempting to access the property "addOption" on an undefined object

Every time I try to implement search functionality, I keep running into this error: "cannot read property 'addOption' of undefined in JavaScript selectize." I have confirmed that my result array does contain data. This is my JavaScript code: ...

How to eliminate rows with images in Exceljs

I created a worksheet with an image in each row. However, when I filter or remove a row, the image for that row stays visible. I tested this on versions v4.4.0 and v4.3.0 I attempted various methods of adding images, but none of them seemed to work. Initi ...

Determine in AngularJS whether there is a checked checkbox in a table row

Here is my HTML code snippet: <tbody ng-repeat="notification in notifications"> <tr> <td rowspan="{{notification.specs.length+1}}">{{notification.notification_id}}</td> </tr> <tr ng-repeat="position in ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...

Discovering the size and count of JavaScript objects within a browser's memory

Many suggest using the Chrome Profiler Heap Snapshot to analyze memory usage, but I have found that on an empty page (no JavaScript or CSS, just HTML), it shows a heap size of 8MB and anywhere from 12 to 30 thousand objects depending on its mood. This tool ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

Is it possible to trigger the @click event in Vuejs when utilizing v-html to render HTML content?

Here is an interesting HTML scenario: errorText: '<a class="button" @click.prevent="enableExceedable(issue.mapping)">Enable exceedable limits</a>'; I am trying to insert this string into the following div: <div v-if="hasIssue != ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

What is the best way to define the starting page in the infinite row model?

As I work with Ag-Grid version 20.0.0 using the Infinite row model and enabled pagination features, I am trying to set the initial page for the first load. However, I have not found any property that would allow me to customize this aspect. The only meth ...

What is the most effective method for coding an input tag with specific restricted characters?

Introduction I have a unique idea for creating an input field of fixed length where users can fill in the gaps without modifying certain pre-filled characters. For example, I want to display "__llo w_rld!" and let users complete the missing characters. In ...

The MaterialUI FormControl API TextField is experiencing an issue where the onClick event does not trigger on the initial click

I am currently working on a React application where I have integrated a MaterialUI Form Control API TextField. However, I am facing an issue with the Select tag as the onClick method is only firing after the first click. There are no hidden CSS properties ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...

What steps are required to transition an Angular application developed without the Angular CLI into an Angular CLI project?

I've created an Angular app using tools like NPM (without utilizing the Angular CLI). What would be the most efficient way to transition this project into the CLI project structure? I want to have the ability to utilize commands like ng serve. ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The communi ...

What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function? Consider defining an object with getter and setter functions like the example below: type Foo = { g ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...