Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
How to initialized an observable for async pipe in the template trying to mimic an assignation in the subscription?

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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'));
about 4 years ago · Juan Pablo Isaza Relatório

0

There are a few approaches to this, but given the code you have provided, you could use the switchMap operator as follows:

Update this.title$ = this.sampleService.loadTitle(); to this.title$.pipe(switchMap(() => this.sampleService.loadTitle()));

What you are doing currently is overwriting the title$ property with a different value. switchMap makes it so that every time the first observable emits a value(in your case this only happens once with your of('Default Title')) it will turn around and create another observable which it will then observe for emitted values.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use ng-container to subscribe to your observable and rename it so that when the data is ready, you can simply use it as a regular variable in the template. stackblitz

container.component.ts

export class ItemsComponent implements OnInit {
  @Input() name: string;
  items$: Observable<string[]>;
  title$: Observable<string>;

  constructor(private sampleService: SampleService) {}

  ngOnInit() {
    this.title$ = this.sampleService.loadTitle();
    this.items$ = this.sampleService.loadItems();
  }
}

container.component.html

<ng-container *ngIf="title$ | async as title">
  <h4>{{ title }}</h4>
</ng-container>

<ng-container *ngIf="items$ | async as items">
  <list *ngIf="items.length" [items]="items"></list>
</ng-container>

Keep in mind that wherever you use the word async, it's a new subscription.

If you use async pipe on the same observable multiple times in your template, you are creating multiple subscriptions.

Using the startWith operator is also a good option if you want to have a different starting value than the one from your service call. A good place to use startWith would be for a formControl valueChanges observable since it doesn't have a starting value and only triggers when there is a value changed.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda