Reputation: 261
I'm retrieving http response and i need to extract the json body into array. I successfully retrieved, but main problem is looping through returned data in map. It is not looping before returning observable.
In server class, I'm getting the json response and notice the for loop, it jumps to return res;
without looping. Also anything i print inside the forLoop
won't work.
getServers() {
return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json')
.pipe(map
(res => {
servers1: any;
servers1 = res;
for (const server of servers1) {
server.name = 'FETCH_' + server.name;
}
return res;
}));
}
In onGet()
, I also tried to loop when i subscribe to it. Still not working
onGet() {
this.serverService.getServers().subscribe(
(response) => {
for (this.server of response) {
this.server.name = 'FETCH_' + this.server.name;
console.log( this.server.name.json());
}
},
(error) => console.log(error)
);
}
I expected this forloop
to work just like below without pipe
. I'm using RxJS 6+
with ..pip(map)..
. It worked when using rxjs-compat
without pipe
getServers() {
return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json').map
(res => {
this.servers1 = res;
for (const server of this.servers1) {
server.name = 'FETCH_' + server.name;
}
return res;
});
}
This is the output.
-LdlacC74PPS93h9HzQc: Array(2)
0:
capacity: 10
id: 1108
name: "Testserver"
__proto__: Object
1:
capacity: 100
id: 953
name: "Liveserver"
__proto__: Object
length: 2
__proto__: Array(0)
-LdnUvw_idV440wn3uIA: Array(2)
0:
capacity: 10
id: 6006
name: "Testserver"
__proto__: Object
1:
capacity: 100
id: 4260
name: "Liveserver"
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object
The name should be FETCH_ Testserver
not just Testserver
.
Upvotes: 1
Views: 555
Reputation: 17504
Try below:
getServers() {
return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json')
.pipe(map
(res => this.transformationMethod(res)));
}
transformationMethod(res){
Object.keys(res.data).forEach(resKey => {
const obj = res.data[resKey];
obj.forEach(data => {
data.name = 'Fetch_' + data.name;
})
})
return res;
}
For data like:
data = {
"data": {
"-LdlacC74PPS93h9HzQc": [{
"capacity": 10,
"id": 1108,
"name": "Testserver"
}, {
"capacity": 100,
"id": 953,
"name": "Liveserver"
}],
"-LdnUvw_idV440wn3uIA": [{
"capacity": 10,
"id": 6006,
"name": "Testserver"
}, {
"capacity": 100,
"id": 4260,
"name": "Liveserver"
}]
}
};
Upvotes: 1