Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a response from http.get to a new instance of a typed object in Angular 2 [duplicate]

I'm trying to get an understanding in how to map the result from a service call to an object using http.get and Observables in Angular 2.

Take a look at this Plunk

In the method getPersonWithGetProperty I'm expecting to return an Observable of type PersonWithGetProperty. However! I can't access the property fullName. I guess that I would have to create a new instance of the class PersonWithGetProperty and map the response to this new object using the class constructor. But how do you do that in the method getPersonWithGetProperty?

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

export class PersonWithGetProperty {
  constructor(public firstName: string, public lastName: string){}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => <PersonWithGetProperty>(response.json()));
    }
}
like image 233
Magnus Wallström Avatar asked May 18 '16 21:05

Magnus Wallström


1 Answers

The problem is that you are coercing the parsed json to behave like the class.

Applying the <PersonWithGetProperty> isn't actually creating a new instance of PersonWithGetProperty it is just telling the compiler to shut up because you know what you are doing. If you want to actually create an instance PersonWithGetProperty you need to construct it with new.

Fortunately you are already half way there, just add another map after you have parsed the output:

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => response.json())
         .map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName));
    }
}

Edit

For this to work you will need to make sure you are using for RxJS 5:

import 'rxjs/add/operator/map'

If you want future safety you should be using the pipe syntax introduced in later versions of RxJS 5

// Either
import {map} from 'rxjs/operators'

return this.http.get('data/person.json').pipe(
  map((response: Response) => response.json()),
  map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName))
);
like image 54
paulpdaniels Avatar answered Nov 03 '22 20:11

paulpdaniels