mysql - Angular2 使用 observables 解析 json 对象

标签 mysql json angular observable

我正在研究 Angular2 和 MySQL,需要一些有关使用 observables 的可注入(inject)服务的建议,

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

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

    }

数据对象

    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 不适用于您所描述的问题。在您的 .map 方法中,您需要添加逻辑来“清理”您认为合适的数据。

例如:

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

关于mysql - Angular2 使用 observables 解析 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42060255/

相关文章:

mysql - 在查询中使用having子句两次

php - 如何防止对自己的帖子进行投票?

arrays - 哪种模型更适合Elasticsearch索引编制?

html - 带有粘性标题和水平、垂直滚动条的垫表

javascript - angular 5 - 仅当数组中存在元素时才添加类

java - 在 Play 2.6.X 中使用数据库调度程序线程池时出现错误

phpMyAdmin 返回空白/白页

c++ - 如何使用 jsonCpp 在 JSON 数据中查找对象或数组的数量

python - 将 Python 字典导出到 Geojson - 从 'coordinates' 值中删除双引号

javascript - 从 RxJS subscribe() 函数访问声明为组件的变量