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

There are no HTTP methods available in the specified file path. Make sure to export a distinct named export for each HTTP method

Every time I attempt to run any code, I encounter the following error message: No HTTP methods exported in 'file path'. Export a named export for each HTTP method. Below is the content of my route.ts file: import type { NextApiRequest, NextApi ...

Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goa ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

The module is missing a declaration file and therefore has an implicit type of 'any'. This error (TS7016) occurs in TypeScript version 2.0

So I've been experimenting with the module react-image-gallery. Surprisingly, there seems to be no types available for this package when trying to install it using npm. When attempting npm install @types/react-image-gallery, all I get is a 404 error. ...

When it comes to TypeScript, there is a limitation in assigning a value to an object key with type narrowing through the

I created a function called `hasOwnProperty` with type narrowing: function hasOwnProperty< Obj extends Record<string, any>, Prop extends PropertyKey, >( obj: Obj, prop: Prop, ): obj is Obj & Record<Prop, any> { return Object ...

tips for managing response time in firebase authentication state

I've been facing an issue with my web application in efficiently checking if it is firebase authenticated. The 'auth state object' doesn't seem to be functioning correctly on my template, as the expected sections are not appearing at al ...

Unleashing the power of await with fetch in post/get requests

My current code has a functionality that works, but I'm not satisfied with using it. await new Promise(resolve => setTimeout(resolve, 10000)); I want to modify my code so that the second call waits for the result of the first call. If I remove the ...

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Node.js is having trouble retrieving information from the SQLite database

Here's a simple code snippet I'm using to retrieve data from my sqlite database. Index.ts: import { Database } from './Class/database'; Database.checkIfExists("some ID"); Database.ts: export class Database { static sqli ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...

If I don't utilize dependency injection in Angular, it prompts me for arguments

Attempting to implement a service like this but encountering some issues translateService = new TranslateService(); An error message pops up stating that there are 9 missing arguments. However, when I modify it to look like this constructor(private trans ...

Determine through programming whether an ng-content slot has been filled in Angular

I have developed a dynamic Angular component that utilizes content projection and slots in the following way: <div class="content-wrapper"> <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1"> ...

What is the method for retrieving interface key types in TypeScript?

My question relates to an interface. interface Some { key1: string key2: number } I am working with a function. const fn = (key: keyof Some) => { return <Some>someObject[key] } Is it possible to determine the return type based on a string ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

The usage of @Inject('Window') in Angular/Jasmine leads to test failures, but removing it results in code failures

Currently, I am encountering a dilemma related to using Angular's @Inject('Window') within a web API service. This particular issue arises when the Window injection is utilized in the service constructor, leading to test spec failures in the ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

Angular is giving me an undefined Array, even though I clearly defined it beforehand

I've been working on integrating the Google Books API into my project. Initially, I set up the interfaces successfully and then created a method that would return an Array with a list of Books. public getBooks(): Observable<Book[]>{ ...

The readline interface in Node that echoes each character multiple times

After creating a node readline interface for my project, I encountered an unusual issue. this.io = readline.createInterface({ input: process.stdin, output: process.stdout, completer:(line:string) => { //adapted from Node docs ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...