2017-02-02 4 views
1

オブジェクトがサーバーから呼び出された後にオブジェクトの値を変更する方法に関するベストプラクティスについて、少し混乱しています。オブジェクトの値がサーバーから要求された後に変更する

マイTSスクリプト:

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") 
     ); 
    } 

} 

マイテンプレート:

<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> 

item.typeは "猫" に等しい場合、どのように、私は "ネコ" と言って、それを修正することができますか? サービスで変更しますか?実際のTSスクリプトですか?パイプを使う?

答えて

5

あなたはforEachのを使用して、サービス内の項目の型の値を変更することができます。

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") 
    ); 
    } 
+0

ありがとうございました:) –

+0

あなたの歓迎:) –

1

あなたはあなたのサービスで配列を変更するArray.map()を使用することができます。

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") 
    ); 
} 
+0

はありがとうございました:) –

関連する問題