我正在研究Angular2和MySQL,需要一些关于使用可观察的可注入服务的建议,
我创建了一个服务来使用getTable()从api获取所有数据,但是现在我不得不实现另一个服务来过滤和解析json数据,并且只使用数据对象中的epoch_time和temp (下面),并使用可观察的方式订阅它。我使用的是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"发布于 2017-02-06 23:48:16
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);
} https://stackoverflow.com/questions/42060255
复制相似问题