Reputation: 3072
I'm a bit confused over the best practice on how to modify a value in an object after it's been called from a server.
My TS Script:
import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { HttpService } from "../http.service";
@Component({
selector: 'app-list-animals',
templateUrl: './list-animals.component.html',
styleUrls: ['./list-animals.component.css'],
providers: [HttpService]
})
export class ListAgentsComponent implements OnInit {
constructor(private httpService: HttpService) { }
items: any[];
ngOnInit() {
this.httpService.getData()
.subscribe(
data => { this.items = data.resource; },
error => alert(error),
() => console.log("Finished")
);
}
}
My template:
<table class="standardTable">
<tr *ngFor="let item of items"><td>{{item.type}}</td><td>{{item.summary}}</td><td>{{item.cost}}</td><td>{{item.available}}</td><td><a [routerLink]="['/animals/edit', item.id]">Now edit an animal</a></td></tr>
</table>
If item.type equals "cat", how and where can I modify it to say "feline"? Do I change it in the service? The actual TS script? Or use a pipe?
Upvotes: 1
Views: 103
Reputation: 917
You can Use forEach and change the value of items's type in your service:
ngOnInit() {
this.httpService.getData()
.subscribe(
data => {
this.items = data.resource;
this.items.forEach(element => {
if(element.type === 'cat'){
element.type = 'feline';
}
return element;
});
},
error => alert(error),
() => console.log("Finished")
);
}
Upvotes: 5
Reputation: 1968
You can use Array.map()
to alter the array in your service:
ngOnInit() {
this.httpService.getData()
.subscribe(
data => {
this.items = data.resource.map(i => {
if(i.type === 'cat') i.type = 'feline'
return i;
});
},
error => alert(error),
() => console.log("Finished")
);
}
Upvotes: 0