【问题标题】:observable with harcoded data可通过硬编码数据观察
【发布时间】:2021-06-10 08:39:31
【问题描述】:

我正在使用版本 10 中的 Angular 应用程序。低于使用硬编码 json 对象学习 observables 而没有 http 调用的要求。例如我有一个接口

export interface cities {
cityId: number;
cityName: string;
}

下面是我声明一个 observable 的代码

cities$: Observable<city[]>;

在 Oninit 方法中,我创建了这样的对象

ngOnInit() : void {
 const cityData = [
  {
     cityId: 1,
     cityName: 'Bangalore'
  },
  {
    cityId: 2,
    cityName: 'chennai'
  }
];

// here i want to get the values in the observables. how can i do it
   this.cities$ = ...
}

下面是html代码

<ul>
  <li *ngFor='let city of cities$ | async'>
     <span [innerHTML] = 'city.cityName'>
   </li>
</ul>

【问题讨论】:

标签: angular rxjs


【解决方案1】:

您可以像这样使用rxjs of 运算符:

this.cities$ = of(this.cityData);

你需要先导入操作符:

import { of } from 'rxjs';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多