Upon subscribing to an observable, the initial value is invariably null

Here is an example of the ProfileService I am currently using:

export class ProfileService {
  private user: BehaviorSubject<User> = new BehaviorSubject<User>(null);

  constructor(private userService: UserService) { 
    this.userService.getUser(1)
      .pipe(map((payload: Payload<Result>) => payload.result))
      .subscribe((User: user): this.user.next(user));
  }

  public getUser() : Observable<User> {
    return this.user.asObservable();
  } 
}

In some components, I inject the AuthorizationService and utilize the authorize method:

export class AuthorizationService {

  user$: Observable<User>;

  constructor(private profileService: ProfileService) { 
    this.user$ = this.profileService.getUser();
  }

  authorize(policy: Policy, data: any) : Observable<boolean> {

    this.user$.subscribe(x => console.log(x)); // ISSUE ARISES HERE
    // Remaining code

  }

}

Challenge
Every time I include console.log in the authorize function, the value of user$ seems to be null initially.

Do you have any insights on why this might be happening?

Answer №1

You've opted to use a BehaviorSubject starting with null as the initial value, which means it will always be the first emission. To prevent this, consider using a standard Subject:

private data = new Subject<Data>();

This will emit every time next is called.

Alternatively, you can use a ReplaySubject:

private data = new ReplaySubject<Data>(1);

By initializing it with 1, it will retain the last value and emit it upon subscription.

Note: Using either approach will result in the loss of access to .value and .getValue().

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

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...

Is it possible to import the identical file twice consecutively using html and typescript?

I encountered an issue with an input element in my HTML file. Here's what it looks like: <input type="file" (change)="receiveFile($event)" id="inputFileButton" hidden /> This input element is designed for users to import files. Wh ...

What is the reason behind Typescript raising an error when attempting to compare two boolean variables with different values (true and false)?

In the screenshot below, you can see that we are encountering a peculiar error when attempting to compare a boolean variable with true. This condition will always return 'false' since the types 'false' and 'true' have no over ...

Utilizing Google's Speech-To-Text for real-time data streaming in Angular

Utilizing the Google Speech-to-Text service through @google-cloud/speech library in my node.js Firebase functions has been helpful, but I am looking to implement it for streaming data which seems impossible with Firebase functions. As a result, I plan to ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

The functionality of 'ngbPopover' in Ng-bootstrap may be affected if the parent container contains a 'transform' css property

Struggling to implement Ng-bootstrap's 'ngbPopover' functionality, I encountered a frustrating issue where the popover would not display after clicking the button. After numerous hours of troubleshooting, I was relieved to discover the root ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

The parameter type 'IScriptEditorProps' does not accept arguments of type 'string'

After trying numerous solutions, I decided to integrate this script editor into a SharePoint site. However, when attempting to implement it, I encountered an issue with the constructor lacking arguments. Despite my efforts to troubleshoot, I have been unab ...

Issue with launching Angular 6 project

I attempted the solution from this link, but unfortunately, it did not work for me. I have cloned a project from GitLab and am attempting to run it. First, take a look at the output of my ng version command: https://i.sstatic.net/qxRzk.png. The project i ...

What is the process for declaring a set in typescript?

In the documentation on basic types for Typescript, it explains using Arrays as a primitive type I am interested in the syntax: const numbers: string[] = [] How can I achieve the same with a set? ...

Angular 8 is throwing a NullInjectorError because it cannot find a provider for AngularFireAnalytics

After running 'npm test', I encountered the following error message: NullInjectorError: StaticInjectorError(DynamicTestModule)[ComparePageComponent -> AngularFireAnalytics]: StaticInjectorError(Platform: core)[ComparePageComponent - ...

How to use D3 to add arrow directions to an SVG path

Within my svg path lies the representation of a shuttle track used in manufacturing processes. Every shuttle on this track moves in a distinct direction, and I wanted the svg path to visually indicate these directions for easy reference. Initially, I tried ...

Preventing Memory Leaks in Single Page Applications (SPAs) Using Google DFP with Angular and Vue: A Guide to Properly Destroying Ads and Their References

I recently encountered an issue while trying to implement Google's DFP in both Vue.js and Angular single-page applications (SPAs) where it appears to be leading to a memory leak. For Angular: I have created a proof of concept which can be found here. ...

Tips for successfully passing function variables as parameters to Angular 2 HTTP subscribe callbacks

I attempted this.propositionService.addProposition(this.proposition) .subscribe(this.addSuccessCallback, this.addFailureCallback); The issue I am encountering is that both addSuccessCallback and addFailureCallback do not have acces ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

Angular 2 - JSON parsing error: Unexpected token < detected at the beginning of the file while interacting with WebAPI [HttpPost]

I'm having trouble making a POST request to my ASP.NET WebAPI endpoint from angular 2 http service. The endpoint doesn't seem to be getting hit at all, despite trying various solutions found in posts. In my angular 2 component, the code for call ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

I'm eager to showcase live, incoming data on the chart. However, I'm feeling a bit lost on how to proceed. Can you help

I am currently utilizing the line chart feature of ng2-charts in my Angular project. However, I am unsure how to create a graph with real-time data. Here is an example of some sample data being used for the line chart: lineChartData: ChartDataSets[] = [ { ...

Transmitting multiple parameters, including a file, from Angular to Spring framework

I am attempting to send an http request with multiple parameters to Spring. One of the parameters is a file, but I keep receiving a bad request error from the server. I am confident that I have made a mistake somewhere, and I would appreciate your assistan ...