The*_*lis 9 observable angularjs ionic-framework es6-promise ionic2
我有一种情况,我需要从Ionic 2应用程序中的存储中获取一段数据,然后使用该数据创建HTTP请求.我遇到的问题是SqlStorage方法返回promises,http meth返回一个observables.我必须做这样的事情才能让它发挥作用:
getToken() {
return this.storage.get('token').then((token) => {
this.token = token;
return token;
});
}
loadStuff(){
return this.tokenService.getToken().then(token => {
return this.http.get("https://www.urltodatasource.com/api/v1/Endpoint?access_token="+token).map(res => res.json());
});
}
Run Code Online (Sandbox Code Playgroud)
然后做这样的事情让它工作:
this.tokenService.loadStuff().then(observable => {
observable.subscribe(data => {
this.storage.set('stuff', data);
return data;
});
})
Run Code Online (Sandbox Code Playgroud)
我对Angular和Ionic一般都是新手,所以我觉得有更好的方法来完成我想要做的事情,但我只是不知道如何做.此外,关于可观察量的所有可用资源都非常快速地变得非常复杂,这使得像我这样容易受到影响的年轻开发人员非常困惑.
任何人都可以更好地了解如何做到这一点吗?谢谢!
Muk*_*kus 11
这是你可以做的:
你的代码如下
getToken() {
return this.storage.get('token').then((token) => {
this.token = token;
return token;
});
}
Run Code Online (Sandbox Code Playgroud)
改变为
getToken: Observable<any> =
Observable.fromPromise(this.storage.get('token').then(token => {
//maybe some processing logic like JSON.parse(token)
return token;
}));
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中,您可以像任何其他可观察的一样使用它.
this.serviceClass.getToken.subscribe(token => {
//whatever you want to with the token
});
Run Code Online (Sandbox Code Playgroud)
在 Angular 2 中,Http服务函数(get、post等)返回一个Observable对象。这就是他们实施的方式。
如果您习惯于 Promise,并且希望您的服务返回 Promise,则可以使用对象toPromise中内置的函数Observable。
loadStuff(){
return this.tokenService.getToken().then(token => {
return this.http.get("https://www.urltodatasource.com/api/v1/Endpoint?access_token="+token).toPromise());
});
}
Run Code Online (Sandbox Code Playgroud)
进而
this.tokenService.loadStuff().then(data => {
data = data.json(); //you might need to do that, depending on the structure of the response
this.storage.set('stuff', data);
return data;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5972 次 |
| 最近记录: |