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

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Ionic Framework: Implementing a search bar in the navigation bar

I am looking to include a search icon in the navbar of my Ionic project <ion-navbar> <ion-buttons left> <button ion-button menuToggle> <ion-icon name="menu"></icon-icon> </button> </ion-bu ...

Error: Attempting to access the 'pipe' property of an object that is undefined in the context of Jasmine and Angular

I'm encountering an issue with unit testing in Angular. Specifically, I'm getting a TypeError: Cannot read property 'pipe' of undefined when trying to test the output of an observable subscribe function. Any assistance on resolving this ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Angular 2 Demonstrate Concealing and Revealing an Element

I am currently facing an issue with toggling the visibility of an element based on a boolean variable in Angular 2. Below is the code snippet for showing and hiding the div: <div *ngIf="edited==true" class="alert alert-success alert-dismissible fade i ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

fusion of Angular and ASP.NET Core

When working with asp.net core and angular, my current process involves: Creating a client app using angular cli Developing an asp.net core mvc app Connecting the two using Microsoft.AspNetCore.SpaServices.Extensions (spa strategy = proxy) Modifying the I ...

Utilizing TypeScript's Exclude feature with a generic type

An update to dependencies in my TypeScript-based Nodejs project has led to compilation errors when working with a generic class that manages mongoose models. The root cause appears to be related to how TypeScript handles generic types. To illustrate the i ...

Angular module with customizable configurations

I am interested in developing a customizable Angular 9 module with IVY and AOT enabled. In the latest version of Angular, IVY and AOT are automatically activated: npx @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8 ...

What is the correct way to assign a property to a function's scope?

Lately, I've been delving into Typescript Decorators to address a specific issue in my application. Using a JS bridge to communicate TS code between Android and iOS, we currently define functions as follows: index.js import foo from './bar' ...

How can I add a JavaScript-created element into a Primeng TurboTable component?

I am in the process of replacing a custom-made table with PrimeNG's turbotable. The issue I'm facing is that when I try to insert buttons into the table that call specific JavaScript functions, they end up displaying as [object HTMLInputElement] ...

Utilize the routerLink within a string value on a HashMap instance

I am currently storing translated parameters in a HashMap object on my component. However, I am facing an issue where certain attributes such as [routerLink] are not functioning properly or not being interpreted by Angular (v5). Here is the code snippet f ...

Using React to iterate over an array of objects and generate Date TextFields in Material UI

I have an array of objects representing different stages in a specific process, each stage identified by an id and name. The structure of the array is as follows: const stages = [ { id: 1, name: initialize }, { id: 2, name: execute ...

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

The power of Typescript shines in its ability to ensure type safety when working with conditional

I am struggling with typing a simple function in Typescript that takes a union type and a boolean as parameters. Here is the code snippet: type A = 'a' | 'A'; function f(a: A, b: boolean): string { if (b) { switch (a) { ...

The DHTMLX Gantt tool is throwing an error message saying "TS6137: Type declaration files cannot be

Lately, I've noticed some issues with my code that were not present before. It seems like something may have changed in either typescript or dhtmlxgantt. Whenever I compile the code, I keep running into these errors: Error TS2306: File 'project ...

Unable to utilize the namespace 'RouteComponentProps' as a specified type

When using TypeScript to define an interface that extends RouteComponentProp, I encountered some issues: VSCode error: [ts] Cannot use namespace "RouteComponentProps" as a type. Console error: Cannot use namespace 'RouteComponentProps' as a typ ...

What is the reason for needing to specify event.target as an HTMLInputElement?

I am currently working on a codebase that uses Material Ui with theme overrides. As I set up my SettingContext and SettingsProvider, I find myself facing some syntax that is still unclear to me. Let's take a look at the following code snippet: const ...

Error: Unable to locate namespace 'google' in TypeScript

I am currently working on an angular-cli project. ~root~/src/typings.json { "globalDevDependencies": { "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459", "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", "sele ...