Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function.

Upon checking, I can see that the method is being called as the response is logged in the console.

errorSubject = new BehaviorSubject<any>(
    {
        exception: false,
        message: '',
        segNum: ''
    }
);
error = this.errorSubject.asObservable();

responseHandler(response) {
    let obj = {};
    if (response.success) {
        return response.payload;
    } else {
        obj = {
            exception: true,
            message: response.exception.message,
            segNum: response.exception.seqNum
        };
    }
    console.log(obj);
    this.errorSubject.next(obj);
}

When subscribing to the error like below:

error;
ngOnInit() {
    this.error = this.apiHandlerService.error.subscribe(obj => {
        console.log(obj);
        if (obj.exception) {
            this.openModal();
        }
    });
}

Every API call goes through this method. If an exception is found, it sends the error details to the modal component, otherwise, it sends the payload.

However, when the else condition is triggered, it appears to be sending the initial value of the errorSubject rather than using the next() method.

Any suggestions on how to fix this?

Following the suggestion provided below, I attempted rearranging the method so that it returns at the end but the issue persists:

responseHandler(response) {
    let obj;
    if (!response.success) {
        obj = {
            exception: true,
            message: response.exception.message,
            segNum: response.exception.seqNum
        };
        console.log(response);
    } else {
        obj = response.payload;
    }
    this.errorSubject.next(obj);
    return obj;
}

Answer №1

A stackblitz has been created using the code provided: https://stackblitz.com/edit/angular4-3tvtrt?file=app%2Fapp.component.ts

In this demo, the responseHandler method is called from the component every 10 seconds, manually passing in the response and incrementing the segNum variable each time. The updated data can be seen in an alert message, confirming that the BehaviorSubject is functioning correctly. If your code resembles this example, the issue could lie with the response from the server. To troubleshoot, check the Network tab in the developer tools to ensure you are receiving the expected data.

EDIT 1

The problem arises in the following section:

if (response.success) {
  return response.payload; // <- HERE
} else {
  ...
}

When a return statement is encountered, the function execution halts at that line, preventing any subsequent code within the function from running. So, when a response with success == true is received, the function stops at return response.payload, bypassing the line this.errorSubject.next(obj).

EDIT 2

A newer version of the demo is available here: https://stackblitz.com/edit/angular4-3tvtrt?file=app%2Fapp.component.ts

In this update, the responseHandler method is triggered with two different parameters alternately. The alert function displays the updated seqNum property as expected. When we do not wish to trigger the Behavior Subject, the console logs "EXCEPTION", whereas it logs "TRIGGER 'NEXT()'" when we do want to trigger it. Make sure to compare your code with this latest example provided to resolve any issues. It is important to ensure that responseHandler triggers itself appropriately, as the rest of the logic appears to be correct.

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

Gathering feedback from a webpage using JavaScript and jQuery

I have been experimenting with different tools such as Selenium and BeautifulSoup in an attempt to scrape the contents of the following website/pages: . Specifically, I am looking to extract the reviews/sections which are dynamically loaded by JS, jQuery ...

Contrasting VSCode Live Server and Node Live Server

Recently delving into the world of JS, I've come across the need to set up a live server using npm. One popular extension in VSCode known as Live Server by Ritwick Dey caught my attention. I'm curious about the distinctions between utilizing this ...

What is the title of the commonly used state management approach in rxjs? Are there any constraints associated with it?

When working with Angular applications, it is common to use the following approach to manage shared states: import { BehaviorSubject } from 'rxjs'; interface User { id: number; } class UserService { private _users$ = new BehaviorSubject([]) ...

Solving the puzzle of complex polymorphic object model deserialization in Java Jackson: Facing the JsonMappingException error – Unexpected token (START_OBJECT) instead

I am working with a hierarchy of objects described as follows: A B extends A C extends B D extends B E extends C F extends A and contains a reference to A The annotation for class A is defined as: @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=Jso ...

Developing and employing Services in Angular 2

Having some trouble with Angular2 as I explore it for the first time, specifically in creating and using a service. I've set up a data service like this: import {Injectable} from 'angular2/core'; import {recentActivity} from './app/com ...

Challenging Issue: "The 'any' type cannot be assigned to the 'never' type"

Currently facing a challenging Typescript problem that has me puzzled. The issue arises at the line themeToChange[tileId][key] = value; The error message states Type 'any' is not assignable to type 'never' This error is directly rela ...

Experiencing a snag with implementing Firebase version 9 FCM in Next.js 12

I decided to incorporate push notifications into my Next.js (version 12) app, so I integrated Firebase Cloud Messaging. Here is the implementation: import { initializeApp, getApp, getApps } from "firebase/app" import { getMessaging, getToken } fr ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

The Nuxt Vuex authentication store seems to be having trouble updating my getters

Despite the store containing the data, my getters are not updating reactively. Take a look at my code below: function initialAuthState (): AuthState { return { token: undefined, currentUser: undefined, refreshToken: undefined } } export c ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...

Developing an export feature for a mean application

Attempting to develop a basic module for organizing accounts on a website seemed like a straightforward task. I thought it would be as simple as creating a file with some functions, wrapping it in module.exports, and everything would work smoothly. However ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

Get an angular xml file by utilizing the response from a C# web API download

I am trying to download an XML file from a database using a Web API in C#, which returns the file as byte[]. How can I properly read these bytes and convert them into an XML file on the client side using Angular? Despite attempts with blobs and other metho ...

What is the best way to organize properties within the Class Variance Authority?

Can the following be achieved in CVA? const mathPanelVariants = cva( 'relative mt-[100px] w-full rounded-sm border-l-[3px] px-[24px] py-[16px]', { variants: { variant: { theorem: { box: 'border-l-[#617bff] dark:bg-[#182 ...

Managing Emitted Events in Vue.js Components within Components: A Guide

I have created a Toolbar Item component as follows: <template> <div class="flex cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 p-1 shadow-sm transition-all duration-300 hover:scale-110 hover:bg-black ho ...

The functionality of the click event attached with the addEventListener is

I have a unique project where I am developing a user interface for a paper-rock-scissor game. To create the UI, I included four buttons: "Start game," "rock," "paper," and "scissor." Initially, I wrote separate code for each button, which worked perfectly ...

A superior method for implementing CSS keyframe transitions

Currently, I am utilizing the Rico St.Cruz brilliant query.transit library for my work. However, I need to make some changes involving classes instead of CSS transitions. Although I am not very confident in CSS transitions, I attempted to replace: JS: $ ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...