Issue with BehaviorSubject<Object[]> causing incorrect array data upon initial subscription

I am facing an issue with a BehaviorSubject where the first .subscribe callback is returning an Array with 6 Objects. Strangely, in console output, it shows length: 6, but every for-loop I iterate through the array only runs 5 times and even when I log arr.length, it outputs '5'.

I'm uncertain how to replicate this problem, but here's the code snippet:

public objects: BehaviorSubject<Object[]> = new BehaviorSubject([]);

// other class
            this.objectService.objects.subscribe(_objects => {
                if (_objects) {
                    for (const obj of _objects) {
                        console.log(obj);
                    }
                    console.log(_objects);
                    console.log(_objects.length);
                }
            });

Output:

How could this discrepancy occur? Various services are writing to this BehaviorSubject using objects.next, so how can I prevent this inconsistency from happening? This issue seems to only manifest when the 'objects' property is updated for the first time. Subsequent updates work fine and display the correct length.

I've also tried using .find and .filter on the array, but they seem to only filter the last 5 entries and not the first one.

Answer №1

It is crucial to ensure that your Behavior subjects are protected or kept private to avoid vulnerabilities.

In this scenario, a behavior subject was created with an initial value of ([]). Upon subscription, the same initial value was emitted ([]). Subsequently, when a new value is emitted using next(), both values are combined resulting in a 6-length array. This unexpected outcome could potentially be avoided if a Subject() is used instead of a BehaviorSubject, unless it's simply a mistake of console.log outputting excessive information.

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

When incorporating @tailwind base, the PrimeNG styles fail to take effect

I have been immersed in a project that combines Angular and Tailwind CSS, and we recently made the decision to incorporate PrimeNG for its useful components. However, we encountered an issue where the styles from PrimeNG were not being applied despite be ...

Issue with form using "target=_blank" to open PDF in web application home screen not functioning properly

I am encountering an issue in my Angular application where a form with target="_blank" successfully returns a PDF upon submission, but when accessed from the homescreen icon of the web-app in Android/Chrome, the new window opens blank without displaying th ...

Passing dynamically loaded parameters to a function during dropdown value selection in Angular 2

Could you please review if I am passing the parameters correctly in the li tag's click function of the updateId method? The console errors only point to that line. This is my app.component.html code: <div class='form-group' style="width ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

New data field is created with AngularFire2 update instead of updating existing field

I am facing an issue with updating a Firestore model in Angular 6. The model consists of a profile name and a list of hashtags. The "name" is stored as the value of a document field, while the "hashtags" are stored as keys in an object. However, every time ...

Is there a way to determine the port being used by the http-server?

After using the command prompt to install the HTTP server with npm install http-server -g, I received a relevant path but no port number. How can I determine what the port number is? http://localhost:8080/index.html I encountered an error on IIS 8.5. ...

What possible reasons could cause the installation of Visual Studio 2017 to disrupt node.js or the typescript compiler?

Recently, I updated to the latest version of Visual Studio 2017 and selected the node.js support option during installation. However, after this update, I encountered issues with the typescript compiler (tsc) in an Angular 2 project that was last modified ...

The command "tsc" was not found in this bash session

Currently, I am using a MAC and attempting to set up TypeScript. I followed the installation process by running sudo npm install -g typescript and received the following output: Password: /Users/<myuserid>/node/bin/tsc -> /Users/<myuserid& ...

Showcasing a roster of contacts within a user-friendly interface, with the opportunity for users to effortlessly include additional individuals

RESOLVED: Special thanks to @Gourav - I simply needed to modify my form data input as shown below: buildFormDynamic(item: Item): FormGroup { return this.fb.group({ data: [item && item.data], }); } UPDATE: While the form builder code seems corre ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

What is the reason that control flow analysis does not support the never type?

Here is the scenario I'm dealing with (utilizing strictNullChecks): function neverReturns(): never { throw new Error(); } const maybeString: string | null = Math.random() > 0.5 ? "hi" : null; if (!maybeString) { neverReturns(); // th ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

Sending data to the makeStyle function in TypeScript

How can I set the style of backgroundImage in my React component based on the value of post.mainImage? Here is the code snippet: import React from 'react'; import { Post } from '../interfaces'; import { makeStyles, createStyles, Theme ...

Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive: @Directive({ selector: '[myRequired][ngControl ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

Injecting services with an abstract class is a common practice in Angular library modules

In my development workflow, I have established an Angular Component Library that I deploy using NPM (via Nexus) to various similar projects. This library includes a PageComponent, which contains a FooterComponent and a NavbarComponent. Within the NavbarCom ...

Unit testing in Angular: Using TestBed to mock asynchronous calls from injected services

Unit tests need to be written for the DataService as shown below: @Injectable() export class DataService { constructor(private config: ConfigService, private http: HttpClient) { } ..... someMethod(){ let apiUrl = this.config.get(&ap ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...