Angular 离子2服务功能在返回前等待localstorage
我从上周开始学习了Ionic 2,现在我在我的服务中创建了一个函数来返回我的API URL,它将检查localstorage是否存储了任何令牌。如果是,则会自动将令牌附加到URL,下面是该函数的代码:Angular 离子2服务功能在返回前等待localstorage,angular,typescript,ionic-framework,ionic2,Angular,Typescript,Ionic Framework,Ionic2,我从上周开始学习了Ionic 2,现在我在我的服务中创建了一个函数来返回我的API URL,它将检查localstorage是否存储了任何令牌。如果是,则会自动将令牌附加到URL,下面是该函数的代码: getApiUrl(method: string){ this.storage.get('user_data').then((val) => { let extUrl: string = null; if(val){ extUr
getApiUrl(method: string){
this.storage.get('user_data').then((val) => {
let extUrl: string = null;
if(val){
extUrl = '?token='+val.token;
}
return "http://localhost/api/"+method+extUrl;
}).catch(err=>{
console.log('Your data don\'t exist and returns error in catch: ' + JSON.stringify(err));
return '';
});
}
但我在控制器中使用以下方法调用此函数:
this.http.post(this.service.getApiUrl("method_name"), data, options)
发生以下错误:
Argument of type 'void' is not assignable to parameter of type 'string'.
我曾尝试将代码更改为使用Promise,但它似乎也不起作用,如何使我的函数等待API URL?您没有从
getApiUrl
方法返回任何内容。在您的getApiUrl
承诺得到解决后,您必须返回承诺并调用您的post
方法:
getApiUrl(method: string){
return this.storage.get('user_data').then((val) => {
let extUrl: string = null;
if(val){
extUrl = '?token='+val.token;
}
return "http://localhost/api/"+method+extUrl;
}).catch(err=>{
console.log('Your data don\'t exist and returns error in catch: ' + JSON.stringify(err));
return '';
});
}
this.service.getApiUrl("method_name")
.then((url) => {
this.http.post(url, data, options);
});