我正在研究 Angular2 和 MySQL,需要一些有关使用 observables 的可注入(inject)服务的建议,
我创建了一个服务来使用 getTable()
从 api 获取所有数据,但现在我不得不实现另一个服务来过滤和解析 json 数据并仅使用 epoch_time
和temp
从数据对象(如下)并使用 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/