简体   繁体   English

Angular2使用Observables解析json对象

[英]Angular2 parsing json object using observables

I am working on Angular2 and MySQL, need some advice on injectable services using observables, 我正在使用Angular2和MySQL,需要有关使用可观察对象的可注入服务的一些建议,

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. 我已经创建了一个使用getTable()从api获取所有数据的服务,但是现在我坚持实现另一个服务来过滤和解析json数据,并且仅使用epoch_timetemp来自数据对象(如下),并且使用Observables订阅它。 I'm using Angular2 V2.2 我正在使用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"

Observable.filter will not work for the problem you are describing. Observable.filter不适用于您描述的问题。 On your .map method you need to add logic that 'cleans' your data as you saw fit. .map方法上,您需要添加逻辑,以根据需要“清除”数据。

eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM