Reputation: 16436
I'm fairly new to Observables, Promises, Angular 2, and Javascript.
My question is how do I get a reference to the "item" object here:
getItemTransactions (item: Item): Observable<any> {
// Do some stuff ...
return this.http.post(this.url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
In the mapped extractData helper?
private extractData(res: Response) {
let json = res.json().body
/// How do I assign back to item object here?
item.some_property = json["some_property"]
}
Code come from here: https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data
Upvotes: 0
Views: 259
Reputation: 62238
.json()
method on the response.subscribe
to then do something with the expected result from .json()
. All of your actions can be done in the expression body, you do not need separate methods for them. This is a mater of preference so whatever you choose is fine.
See code below.
getItemTransactions (item: Item): Observable<any> {
// Do some stuff ...
return this.http.post(this.url, body, options)
.map((res) => res.json()) // get the data from the json result. This is equivalent to writing {return res.json()}
.subscribe((data) => {
this.doSomethingWithData(data, item); // pass that deserialized json result to something or do something with it in your expression
})
.catch(this.handleError);
}
private doSomethingWithData(data: any, item: Item) {
// Do some stuff ...
item.some_property = data["some_property"];
}
Upvotes: 1
Reputation: 14087
Why would you want to re-assign a method parameter in the first place? You probably want to assign a class property instead (this.item
vs item
).
But if for some reason you really want to reassign the item
param, you could always inline the extractData
helper, i.e.:
getItemTransactions(item: Item): Observable<any> {
return this.http.post(this.url, body, options)
.map((res: Response) => {
item = res.json(); // Re-assign some value to `item`
})
.catch(this.handleError);
}
It's probably NOT what you want to do. The usual pattern is to have a function return an observable and subscribe()
to that observable somewhere else in your code. You can do the assignment inside the subscribe callback.
This would translate to the following code:
getItemTransactions(item: Item): Observable<any> {
return this.http.post(this.url, body, options)
.map((res: Response) => res.json())
.catch(this.handleError);
}
// Somewhere else in your code
this.getItemTransactions(item: Item).subscribe(data => {
item = data; // for instance
}
Upvotes: 1