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

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

What is the process for transferring a model and its textures from Blender to three.js?

I am currently facing a challenge with Open/WebGL as I try to display textures/skins from a Blender model in three.js. Despite confirming the successful download of texture files through Chrome's Network tab, they do not appear when rendered. My appr ...

Adding div elements using checkbox switch

In this code snippet, my aim is to display costs based on checkbox selection and generate corresponding totals in the bottom row when the checkboxes are toggled. The goal is to allow users to choose relevant items and have the total cost calculated accordi ...

Express route fails to wait for Redis server response before moving on

How can I modify the code below to ensure that the res.json(...) command is not executed until all open calls to the Redis client.somecommand(..) have completed successfully? An issue occurs in the code where the client.hmset(uname, { ... } attempt to set ...

The autocomplete feature fails to properly highlight the selected value from the dropdown menu and ends up selecting duplicate values

After working on creating a multiple select search dropdown using MUI, my API data was successfully transformed into the desired format named transformedSubLocationData. https://i.stack.imgur.com/ZrbQq.png 0: {label: 'Dialed Number 1', value: &a ...

I am experiencing issues with my buttons not functioning properly after implementing the fetch API in conjunction with express.js

I'm facing a peculiar issue with buttons that are meant to display templates on the client page. This code is executed on the client side. The primary function of this class is to allow the user to click a button, send a request, receive a response c ...

Adjust the header image as you scroll

Currently, I have a static image in the header of the page. I'm looking to have the image change to a different one when half the page has been scrolled. Do I need to utilize JavaScript for this functionality or is it achievable with CSS alone? bo ...

React and Lottie Animation seamlessly synchronized with scrolling movements

I utilized Bodymovin to create various animations and I am hoping to trigger the animation when the scroll reaches that specific point. I have been attempting to find a solution, but unfortunately, I have not been successful. Currently, I am using Gatsby ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

Angular 4: Component Inheritance

I am a newcomer to Angular 4 and currently working on building an application that consists of nearly 50 components. All these components have the same constructor definition, meaning they all inject the same set of services. To simplify this process, I ...

Struggling to pass images from express to Angular6

Snippet of Node.js code app.use('/static/images',express.static(path.join(__dirname,'images'))) Folder Structure |-root | -images When attempting to fetch data in my Angular6+ application, I am utilizing the following ...

The functionality to automatically close the Material Sidebar upon clicking a navigation item is not functioning properly

After navigating by clicking on Sidebar nav items, I am trying to auto close the Material Sidebar. However, it doesn't seem to work in that way for me. I have created a Stackblitz to demonstrate my issue: Access the Stackblitz Editor Site here: http ...

How do I dynamically incorporate Tinymce 4.x into a textarea?

I am encountering a small issue when trying to dynamically add tinymce to a textarea after initialization. tinymce.init({ selector: "textarea", theme: "modern", height: 100, plugins: [ "advlist autolink image lists charmap print p ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...

What is the process for creating an additional username in the database?

As a beginner frontend trainee, I have been tasked with configuring my project on node-typescript-koa-rest. Despite my best efforts, I encountered an error. To set up the project, I added objection.js and knex.js to the existing repository and installed P ...

Jasmine spies falsely report the calling of functions when they have not actually been called

Below is the code snippet I am currently working with: $scope.deleteJob = function(job) { SandboxService.deleteJob(job.id).then(res => { if (res.status == 200) { ngToast.success(); $scope.refreshApps(); } ...

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

Verifying changes using Cypress transformations

I'm brand new to using Cypress and I am currently attempting to verify that one of my elements contains a specific style. The element in question looks like this: <div class="myElement" style="transform: translate(0%, 0px); "></div> Her ...