首页 > 解决方案 > 获取一个可观察到的 HTML

问题描述

我想在 HTML 中显示一个 observable,我的代码不起作用。

@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));}

标签: angularobservable

解决方案


您的实施存在很多问题。

您正在订阅 Observable,它将为您提供 aSubscription而不是Observable.

再加上你想要做的是map一个数组的元素。您将得到的响应map将是一个Array而不是一个数字。

因此,在mapRxjs 运算符中,您还必须使用map数组的运算符。

试试这个:

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)));
}

这是您参考的工作示例 StackBlitz


推荐阅读