How to initialized an observable for async pipe in the template trying to mimic an assignation in the subscription?

Issue

The current code is trying to use the async pipe approach instead of using an assignation in the subscription. But if the delay is happeing in the service, the initial value is not rendering in the template, when the data is ready the value is rendering as expected, I am trying to mimic the rendeing behavior that is presented when I am using this this.title2.

The component:

title$: Observable<string> = of('Default Title'); // I am not sure if this assignation is right
title2 = 'Default Title 2';

constructor(private sampleService: SampleService) {}

// Load title has a delay in the response
this.title$ = this.sampleService.loadTitle();

this.sampleService.loadTitle().subscribe((title) => {
  this.title2 = title; // the assignation 
});

The template:

<h4>{{ title$ | async }}</h4>
<h4>{{ title2 }}</h4>

The sample is in this stackblitz

Solution

I think you want to use startWith that do an initialvalue of an observable.
Try to change the code to this, and it works.

  this.title$ = this.sampleService
      .loadTitle()
      .pipe(startWith('Default Title'));

Answered By – Den

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.