编辑数据服务请求Angular2

时间:2016-05-03 12:35:28

标签: angular angular2-services

我正在接收服务请求中的数据,我想添加一个属性'差异'它。这是我从网址收到的内容:

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

如何调用calculateDifference()函数在返回之前向每个时间集添加属性difference?有没有更好的方法来实现我想要实现的目标?

2 个答案:

答案 0 :(得分:1)

您可以在map运算符中调用它:

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

calculateDifference会根据referencepta属性添加ata属性:

calculateDifference(elt) {
  return {
    pta: elt.pta,
    ata: elt.ata,
    difference: elt.pta - elt.ata // for example
  };
}

答案 1 :(得分: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 || {};
}