在TypeScript Angular中使用Map()方法,在函数中返回Observable数组

时间:2019-05-15 09:08:18

标签: angular typescript dictionary observable

我在服务中使用此方法:

getPriceRules(): Observable<PriceRule[]> {
   return this.http.get<PriceRule[]>(this.url)
   .map(response => PriceRule.fromJson(response));
}

我的错误:

Type 'Observable<PriceRule>' is not assignable to type 'Observable<PriceRule[]>'.
Type 'PriceRule' is missing the following properties from type 'PriceRule[]': length, pop, push, concat, and 26 more.

我想要在getPricesRules()方法中得到PriceRule返回的所有http.get并在每个fromJson中应用函数PriceRule

export class PriceRule {
  public static fromJson(json: Object): PriceRule {
    return new PriceRule(
       json['id'],
       json['activity'],
       json['duration'],
       json['is_indoor'],
       json['surface'],
       json['hour_start'],
       json['hour_end'],
       json['price'],
       json['currency'],
       json['weekdays']
    );
  } 

  constructor(
        public id: string,
        public activity: string,
        public duration: number,
        public is_indoor: boolean,
        public surface: string,
        public hour_start: string,
        public hour_end: string,
        public price: number,
        public currency: string,
        public weekdays: number[]
    ) {}
}

3 个答案:

答案 0 :(得分:2)

您正在将Observable map与数组map混淆:

.map(response => response.map((line) => PriceRule.fromJson(line));

rxjs映射将您的响应映​​射到另一个值,您需要从那里获取数组并将其映射到PriceRule

另一种不需要您的fromJson方法的方法是:

.map(response => response.map((line) => Object.assign(new PriceRule(), line));

另一种方法是使PriceRule成为接口,如果这样做,则不需要任何映射:

return this.http.get<PriceRule[]>(this.url);

注意:您应该尝试更新到最新的rxjs> = 6。为此,您必须将.pipe函数与运算符配合使用

答案 1 :(得分:0)

删除地图

.map(response => PriceRule.fromJson(response));

Angular HttpClient会为您处理

答案 2 :(得分:0)

当您说getPriceRules(): Observable<PriceRule[]>时,表示方法getPriceRules返回Observable,该方法将返回PricesRule[](价格规则数组)。当您在该Observable上调用map时,它将尝试将map函数应用于PriceRule数组(PriceRule []),而不是应用于每个PriceRule对象。此外,Angular会自动完成JSON到对象的转换。因此,删除地图功能。