0

Assume a simple app.component setup where html has something along the lines of.

HTML

<div *ngIf="testObservable$ | async as testObservable">
hello world
</div>

TS

testObservable$: Observable<any>;
_testBehaviourSubject$ = new BehaviourSubject<any>(null);

constructor(public http: HttpClient) {
this.testObservable$ = this._testBehaviourSubject$.asObservable();
}

getData() {
return this.http.get(someApiURL).pipe(tap((e:any) => this._testBehaviourSubject$.next(any));
}

What is the best way to subscribe to getData() to update the BehaviourSubject IF it is null.

Essentially flow would be

listen for BehaviourSubject data as BSDATA
Event 1
    BSDATA is null
        do getData()
Event 2
    BSDATA is not null
        display 'Hello World'

Ideally I'd like to leverage the async pipe as opposed to triggering subscribe event manually. Advice appreciated.

Aeseir
  • 7,754
  • 10
  • 58
  • 107
  • 1
    I think we're missing some information there. Why do you need `BehaviourSubject` at all? Seems you could just do: `this.testObservable$ = this.http.get(someApiURL)` – Kamil Chlebek Jun 04 '22 at 07:32
  • Sure, the intent behind behaviour subject is for data be shared across components. My next step is to migrate the BehaviourSubject to a service. That after it is loaded in first time by Component A, all others can use the same entity without calling server. – Aeseir Jun 04 '22 at 08:39
  • Then you can use `shareReplay` operator from `rxjs`. Here's an example: https://stackoverflow.com/a/51044495/9932919 – Kamil Chlebek Jun 04 '22 at 09:28

0 Answers0