2016-05-03 9 views
0

サービスリクエストからデータを受信しましたが、「差異」属性を追加します。これは私がURLから受け取るものです:データサービスリクエストを編集するAngular2

{ 
    "times" : [{ 
     "pta" : "12:05", 
     "ata" : "12:34" 
    },{ 
     "pta" : "14:40", 
     "ata" : "14:36" 
    },{ 
     "pta" : "12:05", 
     "ata" : "12:10" 
    },{ 
     "pta" : "18:30", 
     "ata" : "20:00" 
    }] 
} 

これは私のサービスです。

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class TimesService { 
    constructor(private http: Http) { } 

    private _timesUrl = './app/api/times.php'; 

    calculateDifference(data: any): any { 
     // Code to calculate difference here 
     // Return object with pta, ata, difference properties 
    } 

    getTimes(): Observable<any[]> { 
     return this.http.get(this._timesUrl) 
      .map(this.extractData) 
      .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     if(res.status < 200 || res.status >= 300) { 
      throw new Error('Bad respons status: ' + res.status); 
     } 
     let body = res.json(); 
     return body.data || {}; 
    } 

    private handleError(error: any) { 
     // In a real world app, we might send the error to remote logging infrastructure 
     let errMsg = error.message || 'Server error'; 
     console.error(errMsg); // Log to console instead 
     return Observable.throw(errMsg); 
    } 
} 

私はそれが返される前に、すべてのtimesetにプロパティdifferenceを追加するcalculateDifference()関数を呼び出すことができますどのように?達成しようとしていることを実装するためのより良い方法はありますか?

答えて

1

あなたはmapオペレータでそれを呼び出すことができます。

.map(data => { 
    data.times = data.times.map(elt => this.calculateDifference(elt)); 
    return data; 
}) 

calculateDifferenceptaataプロパティに基づいてreferenceプロパティを追加します。

calculateDifference(elt) { 
    return { 
    pta: elt.pta, 
    ata: elt.ata, 
    difference: elt.pta - elt.ata // for example 
    }; 
} 
1
getTimes(): Observable<any[]> { 
    return this.http.get(this._timesUrl) 
     .map(data => this.extractData(data)) 
     .catch(this.handleError); 
} 


private extractData(res: Response) { 
    if(res.status < 200 || res.status >= 300) { 
     throw new Error('Bad respons status: ' + res.status); 
    } 
    let body = res.json(); 
    body.times.forEach(value => { 
     value.difference = this.calculateDifference(value.pta, value.ata) 
    }); 
    return body.data || {}; 
}