What is the best way to notify the parent Observable of an inner Observable’s error or success within nested Observables?

How can the outer Observable be notified of success or error in nested Observables?

Why are onNext and onCompleted undefined within the inner Observable?

public updateDocument(item: Document): Observable<any> {
    this.firstUseOfflineContainer();
    let afiEdit = this.offlineData.afi.edit;

    //outer observable
    return Observable.create(observer => {
        //inner observable
        this.dataService.updateRequest(item).subscribe(
            (next) => {
                console.log("ok");
            },
            (err) => {                
                afiEdit.headers.push(item);
                //how to throw error to outer observable
            },
            () => {
                observer.onNext(item);
                observer.onCompleted();
            }
        );

        return () => console.log('cleanup message')
    });
}

Answer №1

It appears that your objective is to trigger an error in the main observable when there is a failure in the sub-observable.

The code implementation for this scenario would resemble the following:

// Define the sub-observable (potentially an HTTP request)
// I simulated the call's success or failure with a random 50/50 chance
var innerObservable = new Rx.Observable(observer => {
  var didMockCallFail = Math.random() < .5; 
  if(didMockCallFail){
    console.log('Sub-observable call failed');
    observer.error(new Error('Call failed!'));
  } else {
    console.log('Sub-observable call was successful');
    observer.next({lolData: 'I am data'}); 
  }
})

// Define the main observable which subscribes to the sub-observable
var outerObservable = new Rx.Observable(observer => {
  innerObservable.subscribe(
    data => observer.next(data),
    err => observer.error(err)
  )
});

outerObservable.subscribe(
  next => console.log('Received data!'),
  err => console.error('Oops, something went wrong')
);

Moreover, to pass parameters to Observables and enhance reusability while avoiding global scope, you can utilize a generator function like so:

function makeObs(someParam){
  return new Rx.Observable(observer => {
    observer.next(someParam);
  })
}

If you require further clarification, feel free to ask.

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 eliminate file nesting in Visual Studio 2017

Is there a way to prevent certain file types from being nested within other files, such as .ts files not being nested beneath .html files? I came across this request, but has anyone found a solution to achieve this? ...

Use an extension module in a Node.js script

I am currently working on integrating babylon.js into my Node.js Angular application. Current Integration Process 1) I have installed the babylon.js npm repository in my project's node modules using npm install --save babylonjs. The image below i ...

"Capture input value changes and display the previous value when submitting a post. See an example of

Hi there! I'm facing 2 issues with my code, you can find a DEMO here When adding a product to the sale form, the input field for `description` changes for all products. Changing the input product in the sale does not reflect the change. I have shar ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

Looking to retrieve the request body in a route handler in Next.js version 13.2?

I encountered an issue while attempting to send a post request to my API. The problem arises when I try to access the request body within the route handler, resulting in the following error: Code: export async function POST(request: Request) { const ...

The mat-table component in my HTML code is not displaying the dataSource as expected, even though I meticulously copied it from Material Angular

Although I am aware that my question may seem unusual, my issue precisely matches what the title conveys. The problem lies in my mat-table dataSource not displaying any data, even after attempting to log the data with console.log("My Data : ", this.dataSou ...

Union types discriminate cases within an array

Creating a union type from a string array: const categories = [ 'Category A', 'Category B' ] as const type myCategory = typeof categories[number] myCategory is now 'Category A' | 'Category B' Now, the goal is ...

Trouble with displaying points in Angular2's highcharts

I have implemented the angular2-highcharts chart module in my angular2 web application. Everything works fine when the graph has less than 7000 points, with the line and points displaying correctly. However, once the number of points surpasses 7000, there ...

What is the best way to maintain the order of variadic types for conditionally inferred conditional types?

Here is the type definition that I am working with: type Inner<Type> = Type extends Wrapper<infer U>[] ? U[] : never; Additionally, I have a function with the following signature: function myFunc<From extends Wrapper[], To>( values: ...

Rxjs: handling arrays of observables by processing them in batches

I am facing a scenario where I have an array of observables. Let's say: const responses$: Observable<Response>[] = [ this.service.get(1), this.service.get(2), this.service.get(3), this.service.get(4) ]; My goal is to process ...

It seems that an error has occurred: DOMException was thrown because the attempt to run 'importScripts' on 'WorkerGlobalScope' has failed. The script located at 'http://localhost:4200/BlinkCardWasmSDK.js' was unable to load properly

Recently, I attempted to integrate this credit card reader into my Angular application. Despite carefully following all the installation steps and obtaining a valid license key, I encountered the following error: Error during the initialization of the SDK! ...

Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message: Cannot read property 'populationService&a ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Steps for setting up tsconfig.json for Chrome extension development in order to utilize modules:

While working on a Chrome plugin in VS Code using TypeScript, I encountered an issue with the size of my primary .ts file. To address this, I decided to refactor some code into a separate module called common.ts. In common.ts, I moved over certain constan ...

Exploring techniques to retrieve data from Json Array in Angular using Firebase documentation

this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(); When I include it in my component.html file like this: {{ currentUser$|async|json}} The output I get is as follows: { "photoUrl": "", &qu ...

typescript: tips for selecting a data type within an object

I need help extracting the type of the 'name' property from an object belonging to the Action interface. interface Action { type: string, payload: { name: string } } I attempted to use Pick<Action, "payload.name">, but it didn&apos ...

Creating an interface and setting a default value

I am exploring the use of interfaces in my models and want to establish a default value for them. export interface IPerson { id: string; name: string; } class Person implements IPerson { id = ''; name = 'John'; } export cla ...

Guide on incorporating Paddle into your SvelteKit project

I'm struggling to implement a Paddle Inline Checkout in SvelteKit. Every time I try, I keep encountering the error message Name Paddle not found. It seems like the script is not functioning properly. Console Error: Uncaught (in promise) ReferenceErro ...

Creating a null array of a specific size can easily be accomplished in Typescript

When I use the splice method to add elements to an array at a specified index, I find myself creating a null array first in order to achieve this. If I use an empty array instead, the elements do not get pushed to the specific instance that I intended. Cur ...

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...