I have a setup like this
- api.service (wraps the httpClient Module)
- customer.service
the api service get looks like this:
get<T>(url: string, options?) {
return this.httpClient.get<T>(this.apiUrl + url, this.getOptions(options));}
in my customer.service I have:
private fetchCustomer(access_token: String): Observable<Customer> {
const options = { headers: new HttpHeaders({ Authorization: 'Bearer ' + access_token }) };
return this.http
.get<Customer>('customers/me', options)
.map(res => {
const customer = res.data;
customer.access_token = access_token;
return customer;
})
.catch(this.handleError.bind(this));
}
and it give me this error:
[ts]
Property 'data' does not exist on type 'HttpEvent<Customer>'.
Property 'data' does not exist on type 'HttpSentEvent'.
The new HttpClient in Angular 4.3 has currently 3 protoypes for
get<T>
They are
The Comments at the top of client.d.ts state this.
The really important part is the observe parameter
get<T>(url, {observe: 'events'})
returnsHttpEvent<T>
get<T>(url, {observe: 'response'})
returnsHttpResponse<T>
get<T>(url, {observe: 'body'})
returnsT
Note: if you subclass the options part into a method you must return a type of Object, without that the compiler will automatically select the first method which happens to return
HttpEvent<T>
so
and
will compile to the wrong interface and return
HttpEvent<T>
, butand
will return
T
andHttpResponse<T>
respectivelyLooking at the angular source code (v4.3.3), when you wrap the http.get without specifying the type of
options
the typescript compiler is using this type definitionTo get the typescript compiler to use the correct type definition, you can specify that the options is of type Object. In your case the getOptions method should specify it is returning the type Object.
Now the typescript compiler will find the correct type definition
and finally now you can access data
The solution is to use the new way of getting the json data....
First convert the data to a javascript object using the json method. Then get the data you need using subscribe.