Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 离子2服务功能在返回前等待localstorage_Angular_Typescript_Ionic Framework_Ionic2 - Fatal编程技术网

Angular 离子2服务功能在返回前等待localstorage

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

我从上周开始学习了Ionic 2,现在我在我的服务中创建了一个函数来返回我的API URL,它将检查localstorage是否存储了任何令牌。如果是,则会自动将令牌附加到URL,下面是该函数的代码:

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