Issue with subject returning as undefined within the constructor

Having an issue with using a Subject to track if a user is authenticated. The problem arises when the subject returns undefined upon reloading after subscribing in a component.

Below is my approach: I check for user data in local storage and set the Subject to true if the data is present.

user.service.ts

public auth_status:Subject<boolean> = new Subject<boolean>();

getCurrentUser(): User {
    let storage =  localStorage.getItem('current_user');

    if (storage) {
        return Json.parse(storage);
    } else {
        return null
    }
};

getUserAuth() {
    if (this.getCurrentUser() != null) {
        this.auth_status.next(true);
        console.log(this.auth_status);
    } else {
        this.auth_status.next(false);
        console.log(this.auth_status);
    }
    return this.auth_status;
}

navbar.component.ts

constructor(private _userService: UserService) {
    this._userService.getUserAuth().subscribe(data => this.auth_status = data);
}

this.auth_status controls an *ngIf in the navbar which displays either a sign-in or sign-out button

I've also attempted calling the method before subscribing, but it didn't resolve the issue.

Any insights are appreciated! Thanks!

Answer №1

Before the subject is returned, events are emitted, so when you call subscribe() in the constructor, the events have already passed.

To prevent this, you can utilize a BehaviorSubject like so:

public auth_status:Subject<boolean> = new BehaviorSubject<boolean>(null);

A BehaviorSubject immediately emits the last event to new subscribers once they subscribe.

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

Saving the name and corresponding value of a selected option element into separate fields using Angular framework

I have implemented the following code to generate a select field. The ngModel is successfully updating the value, but I am also looking to capture the name of the selected option and store it in a different field. Is there a solution to achieve this? ( & ...

Error: Unhandled promise rejection: Trying to access a property of null (specifically 'branch') causing a TypeError

While developing a dashboard for an Angular application, I encountered an error when trying to access the dashboard: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'branch') TypeError: Cannot read propert ...

Limit the types of components allowed as children in a React component by utilizing TypeScript

I've been struggling with this question for a while, searching through answers but still unable to get my code to work. Here's the issue at hand. Within my code, I have a component called Steps which acts as a wrapper. I also have multiple Step ...

Mapped types in TypeScript are utilized to create an object representation that includes optional Observables with keys mapped as string literals

I am in need of a customized type to depict an object where the properties can optionally be RxJS Observables. The most straightforward approach to accomplish this is by using the following type: type OptionalObservables<T> = { [K in keyof T]: T[ ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

Integrate additional attributes into the interface object in TypeScript on-the-fly without modifying the existing class

I'm faced with a situation where I cannot modify the class below. export class Cars implements Vehicales { color?: string; type?: string[]; } The templates object is passed to kendoReactGrid which contains column strings, and I need to add a ...

Utilizing cellRendererParams in Ag-Grid version 19 with Angular 6 to execute a function within my component

One issue I encountered in my Ag-grid column was when I added a component that required calling a function from my controller. While I could access the controller without any issues, attempting to call another function proved problematic. This occurred bec ...

Angular Universal pre-renders routes with an empty router-outlet, ensuring fast initial page loads

After transitioning to Standalone APIs with Angular 16, I encountered a strange issue: SSR works perfectly as expected (with clientHydration()), but when attempting SSG (prerender), everything seems to crumble, and the lack of errors makes it hard to pinp ...

Reactive forms with Angular CDK drag and drop

I'm facing an issue in this scenario: https://stackblitz.com/edit/angular-asevei?file=app%2Fcdk-drag-drop-sorting-example.html Everything seems to be functioning properly, except that when I drag the select box, it keeps resetting to the first value ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

Typescript encountering difficulty in accessing an array saved in sessionStorage

Imagine you have an array stored as a string in session storage, and you need to retrieve it, add an element, and then save it back. trackNavHistory = (path: String) => { let historyArr : Array<String> = sessionStorage.getItem("navHistory ...

Using callback functions with server.listen in Typescript and JavaScript

I'm puzzled why the following codes are not functioning in TypeScript. (They used to work perfectly fine in my previous JavaScript code!) http.createServer(app).listen(port, (err) => { # Do something }); However, this code works flawlessly (wi ...

Implementing Authorization keys in Angular's Swagger UI using code

I am currently in the process of integrating swagger ui into an Angular 7 application. Utilizing the npm package swagger-ui 3.37, the API documentation is structured with swagger 2.0. The integration works smoothly when authorization is not required within ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Observable doesn't respond to lazy loaded module subscriptions

I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service. index.ts export { TestComponent } from './test.component'; export { ...

I'm struggling with finding an answer to this question: "What is the most effective way to conduct a

I'm experimenting with a file upload. I decided to encapsulate the FileReader() inside an observable based on information I found in this discussion thread: onFileSelected(event: any) { this.importJsonFileToString(event.target.files[0]) .p ...

Enhancing the appearance of Angular Material components through nested components

HomeComponent has templates that include a router outlet /* home.component.ts */ ... <mat-sidenav-container> <mat-sidenav-content> <router-outlet></router-outlet> </mat-sidenav-content> </mat-sidenav-container&g ...

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...