Angular2使用observable解析json对象

时间:2023-01-03 21:18:51

I am working on Angular2 and MySQL, need some advice on injectable services using observables,

我正在研究Angular2和MySQL,需要一些关于使用observables的注射服务的建议,

I have created a service to get all the data from the api using getTable(), but now I'm stuck with implementing an another service to filter and parse the json data and use only epoch_time and temp from the data object (below) and subscribe to it using Observables. I'm using Angular2 V2.2

我已经创建了一个服务来使用getTable()从api获取所有数据,但是现在我不得不实现另一个服务来过滤和解析json数据并仅使用来自数据对象的epoch_time和temp(下面)和使用Observables订阅它。我正在使用Angular2 V2.2

service.ts:

service.ts:

@Injectable()
export class TabuleService {

      //private headers = new Headers({'Content-Type': 'application/json'});
      private _Url = 'http://localhost:3000';  // URL to web api

      constructor(private _http: Http) {}

      getTable(): Observable<Tabule[]> {
        const url = this._Url+'/temperature';
        return this._http.get(url)
                   .map(res => res.json())
                   .catch(this.handleError);
      }

       getTemp(): Observable<testing[]> {
        const url = this._Url+'/temperature';
        return this._http.get(url)
                   .map(this.extractData)
                   //.filter(temp=>temp.mac==='3s-ds-23-sf-23-ce-32')
                   .catch(this.handleError);
      }            

    private extractData(res: Response){
      let body =res.json();
      console.log(body.data);
      return body.data || { };

    }

data Object

数据对象

    epoch_time_stamp:1486257208633
    mac:"3s-ds-23-sf-xx-xx-xx"
    task_id:2
    temp:"23"
    time_stamp:"2017-02-05T01:13:28.000Z"

    epoch_time_stamp:1486257208733
    mac:"3s-ds-23-sf-xx-xx-xx"
    task_id:3
    temp:"26"
    time_stamp:"2017-02-05T01:15:28.000Z"

1 个解决方案

#1


0  

Observable.filter will not work for the problem you are describing. On your .map method you need to add logic that 'cleans' your data as you saw fit.

Observable.filter不适用于您描述的问题。在.map方法中,您需要添加逻辑,以便在您认为合适的情况下“清理”您的数据。

e.g.:

例如。:

getTemp(): Observable<testing[]> {
    const url = this._Url+'/temperature';
    return this._http.get(url)
        .map(res => {
            let temp = res.json();
            //Add logic here that loops through temp and cleans value
            return temp;
            }).catch(this.handleError);
        }   

#1


0  

Observable.filter will not work for the problem you are describing. On your .map method you need to add logic that 'cleans' your data as you saw fit.

Observable.filter不适用于您描述的问题。在.map方法中,您需要添加逻辑,以便在您认为合适的情况下“清理”您的数据。

e.g.:

例如。:

getTemp(): Observable<testing[]> {
    const url = this._Url+'/temperature';
    return this._http.get(url)
        .map(res => {
            let temp = res.json();
            //Add logic here that loops through temp and cleans value
            return temp;
            }).catch(this.handleError);
        }