Managing various situations using observables

Currently facing a coding dilemma: I have an observable that I need to subscribe to and certain requirements must be met:

1 - The registerUser function should only execute after processing the callback data.

2 - If registerTask returns data, I receive an ID and then need to call registerUser, which is also an observable.

3 - In case of an error returned by registerTask, I have to call searchTaskByID to get an ID before calling registerUser.

The issue lies in not wanting to duplicate the code for registerUser within both the data and error branches. Is there a simpler way to ensure its execution regardless of the conditions above? Any suggestions?

Here's the current code snippet I am working with, but it's not functioning as intended:

Angular 2 component:

taskID:String

constructor(
    private myService:MyService,
    private router:Router
) { }

onClick() {

   const task= {
       name: this.taskID,
   }
   const user= {
       name: "test",
   }

   return this.myService.registerTask(task).subscribe(
       (data) => {console.log(data)
           var taskId = data.taskId
       },
       (error) => {console.log(error)

           this.myService.searchTaskByName(task).subscribe(
               (data) => {console.log(data)
                   var taskId = data.id
               },
               (error) => {console.log(error)},
               ()=>{}
           );
       },
       () => this.myService.registerUser(user).subscribe(
           (data) => {console.log(data)
               var userId = data.id
           },
           (error) => {console.log(error)}
       )

   )
}

Answer №1

When dealing with errors, the Observable operator catch comes in handy.

I created a demo where you can trigger an error scenario by using the second argument of registerTask().

function registerTask(task:string, forceError = false) {
    // console.log('registerTask called');
    return Observable.defer(() => {
        return Observable.of(1).delay(1000)
            .map(value => {
                if (forceError)
                    throw 'ERROR';
                return value;
            });
    });
}

function registerUser(user:string) {
    // console.log('registerUser called');
    return Observable.of('userID').delay(1000);
}

function searchTaskByName(task:string) {
    // console.log('searchTaskByName called');
    return Observable.of(2).delay(1000);
}

// registerTask('task', true)  // forceError
registerTask('task')
    .catch((err, caught) => {
        return searchTaskByName('task');
    })
    .mergeMap(taskID => {
        console.log(`taskID = ${taskID}`)
        return registerUser('user');
    })
    .subscribe(userID => console.log(userID));

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

How to make an HTTP request only once after a certain period of time

I have an Angular 11 component with multiple dynamically included inputs in a table. After the user enters a currency value into any of these inputs, I make an API call to calculate the total. The issue is that I am calling the API multiple times, so I wa ...

Accessing a variable within a function in Angular

Recently I started working with Angular and encountered an issue while trying to access a variable inside a function. Below is the code snippet that's causing me trouble: mergeImages() { var imgurl; var canvas: HTMLCanvasElement = this.canv ...

How can I retrieve the ngx-Summernote runtime value?

I am currently integrating ngx-Summernote into my Ionic 5 + Angular project. Is there a way to access the value using ngModel? I attempted: <div [ngxSummernote]="config" [ngxSummernoteView]="content"></div> The issue I&apo ...

"Unsuccessful API request leads to empty ngFor loop due to ngIf condition not being

I have been struggling to display the fetched data in my Angular 6 project. I have tried using ngIf and ngFor but nothing seems to work. My goal is to show data from movies on the HTML page, but for some reason, the data appears to be empty. Despite tryin ...

Extract information from a complex nested structure within an array

Can someone assist me with extracting only the username from the response provided below? I am able to access other data but struggling with this particular aspect. [ { "_id": "5f44d450aaa72313549d519f", "imageTitle": "u ...

Facing a Timeout Issue while Testing an Angular application using Protractor

When working with an Angular application and setting browser.waitForAngularEnabled(true), I encountered the following error after clicking on an element: ScriptTimeoutError: script timeout (Session info: chrome=85.0.4183.121) Driver info: chromedriver=85.0 ...

Vertical and horizontal tabs not functioning properly in Mat tabs

I successfully created a vertical material tab with the code below, but now I am looking to incorporate a horizontal tab inside the vertical tab. Attempting to do so using the code provided results in both tabs being displayed vertically. Below is my code ...

What could be causing the error "Type 'String' cannot be used as an index type" to appear in my TypeScript code?

My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement. I've searched for solutions and come across sugges ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

The Java Spring and Angular 7 application is missing a necessary file request component

I am facing an issue with the POST method in Angular 6. I am trying to send an image to the server. When I test it using Postman, my Spring Boot application works perfectly and saves the image on the server. However, when I attempt to send the image from m ...

The issue arises when IonViewDidLoad fails to retrieve data from the service class in Ionic after the apk file has been generated

Creating a form where users can input various information, including their country code selected from dropdowns. Upon submission, the data is displayed successfully when running in a browser. However, after building the apk file, the country codes fail to ...

Getting around relative paths in an Angular application hosted by NGINX

I am using NGINX to host my Angular application. The frontend is accessible at http://localhost/, and the backend can be accessed at http://localhost/api/. While most of my configuration works correctly, I am encountering an issue with a relative path in a ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...

The hook from Supabase is facing issues with proper importing

This project is a Spotify clone. The issue I'm facing is related to importing the hook. The error message reads: React Hook "useSupabaseClient" is called in function "useloadArtistImage" that is neither a React function component nor a custom React H ...

Angular - Enhancing the page with valuable information

Recently, I've been developing an Angular application that is designed to function as a digital magazine. This app will feature articles, news, reviews, and more. Along with this functionality, I am looking to include an admin panel where I can easily ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

NPM packages: Providing a comprehensive assets and images delivery solution package

After creating a custom (angular2) npm package and uploading it to my personal registry, I encountered an issue with delivering the icons along with the component. The component should display an icon by using the following template: <span [class]="& ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

"RxJS in Angular 2: The elusive map function seems to be missing

Issue: Received an error stating, "Property 'map' does not exist on type 'Observable'." import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; decl ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...