Reputation: 3169
I have a Class Like
export class R {
constructor(
public id: Number,
public dte: Date,
) { }
}
a service That return R[] the code is like :`
return this.http.get(this.serverLocal).map(this.formatDate);
formatDate(res: Response) {
const data = res.json() as R[];
data.forEach(D => {
D.dte = new Date(D.dte);
})
return data;
}
I get the 2 errors: property 'dte' does not exist on type 'R'. I changed a lot of code for no avail. It's working if I do some change with ID, but not with dte date. What am I doing wrong?
Upvotes: 0
Views: 914
Reputation: 3975
Before answering, take a look at HttpClient if you are using Angular 5 as json()
is no more needed. An http get already returns a json by default.
If your json response has only these two entries (id
and dte
) you simply have to do the following:
. . .
import { HttpClient } from '@angular/common/http';
/** rxjs **/
import { Observable } from 'rxjs/Observable';
getStuff(someUrl: string): Observable<Array<R>> {
return this.http.get(someUrl);
}
If you need some error handling or, for instance, retry if the request gives error your should do something like:
. . .
import { HttpClient } from '@angular/common/http';
/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';
getStuff(someUrl: string): Observable<Array<R>> {
return this.http.get(someUrl)
.pipe(
retryWhen(errors =>
// Do Stuff
),
catchError((error: Error) => {
return Observable.throw(error);
})
);
}
There is no actual need of mapping data, but, if you would like to do it, you should do like":
data.map((dataEntry) => new R(dataEntry))
If you are still using Angular 4.x.x, you should get it going with:
. . .
import { Http } from '@angular/http';
/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';
getStuff(someUrl: string): Observable<Array<R>> {
return this.http.get(someUrl)
.pipe(
map((response: Response) => response.json()),
catchError((error: Error) => {
return Observable.throw(error);
})
);
}
Upvotes: 1