Reputation: 13
Hi guys I want to ask you about verry basic question, my API server is returning response from server
In my angular service I am making successfull request to get this data from server:
get() {
return this._$http({
url: `${this._AppConstants.api}/calendar`,
method: 'GET'
}).then(
(res) => {
let events = [];
return res.data;
}
)
}
But I want to assign response to my events
object. Let's say my server is returning (as you can see in the screenshot) the objects but I want to transform them to look something like this:
{
title: res.data.description,
startsAt: res.data.startdate,
endsAt: res.data.enddate
}
I dont have any idea how to transform the objects from server to working arrays
Upvotes: 0
Views: 2527
Reputation: 526
You could return an observable:
events.service.ts
events(){
return this.http.get(this.eventsUrl)
.map((response: Response) => response.json())
}
and then subscribe to it in your component:
event.component.ts
export class EventComponent{
events = []
constructor(private eventSvc:EventService){
eventSvc.subscribe(
events => this.events = events
)
}
}
Upvotes: 0
Reputation: 60518
Alternatively, you could use observables and an approach like this:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
The map operator on the observable maps the response to an array of product objects as defined in the IProduct interface.
Upvotes: 1
Reputation: 3907
Depending on what you exactly want, you could just pass in a new object.
events.push({
title: res.data.description,
startsAt: res.data.startdate,
endsAt: res.data.enddate
})
Keep in mind, your events
variable is declared inside of your .then()
function, so it won't expose its value(s).
Upvotes: 0