Fealo
Fealo

Reputation: 99

Using Map() method in TypeScript Angular, returning array of Observable in a function

I have this method in my service :

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

My error :

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.

What I want in my getPricesRules() method is get all PriceRule that the http.get returns me and to apply my function fromJson in each 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[]
    ) {}
}

Upvotes: 0

Views: 10413

Answers (3)

Poul Kruijt
Poul Kruijt

Reputation: 71911

You are confusing the Observable map with the array map:

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

The rxjs map, maps your response to another value, from there you need to take your array, and map it to the PriceRule.

Another way of doing this, which does not require your fromJson method is:

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

Another way, is to make the PriceRule an interface, if you do that, you don't need any mapping:

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

note: you should try to update to the latest rxjs >= 6 though. With that you have to use the .pipe function with operators

Upvotes: 3

Praveenkumar
Praveenkumar

Reputation: 2182

When you say getPriceRules(): Observable<PriceRule[]>, what it means is the method getPriceRules returns Observable that will return PricesRule[] (price rule array). When you call map on that Observable, it tries to apply the map function to PriceRule array (PriceRule[]) and not to each PriceRule object. Also, JSON to object conversion is done by Angular automatically. So, remove the map function.

Upvotes: 0

Marcel Hoekstra
Marcel Hoekstra

Reputation: 1488

Remove the map

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

Angular HttpClient will handle that for you

Upvotes: 0

Related Questions