Pseudalitos
Pseudalitos

Reputation: 45

Get an observable into HTML

I want to show an observable in HTML, my code is not working.

@Component({
  selector: 'app-root',
  template: '<p *ngFor="let test of map | async">Hier kommt: {{test}}</p>',
  styleUrls: ['./app.component.css']})

export class AppComponent{
public sourceOne = of(4, 5, 6 );
public map = this.sourceOne.pipe(map(val => val * 10)).subscribe(val => console.log(val));}

Upvotes: 0

Views: 668

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39482

There are a lot of issues with your implementation.

You're subscribing to the Observable which will give you a Subscription instead of an Observable.

Plus what you want to do is map the elements of an Array. The response that you'll get inside map would be an Array and not a number.

So inside that map Rxjs Operator, you'll have to use the map Operator of an Array as well.

Give this a try:

import { Component } from '@angular/core';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: '<p *ngFor="let test of map | async">Hier kommt: {{test}}</p>',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  public sourceOne = of([4, 5, 6]);
  public map = this.sourceOne.pipe(map(res => res.map(num => num * 10)));
}

Here's a Working Sample StackBlitz for your ref.

Upvotes: 2

Related Questions