Ionic 2中的本地存储无法访问then()方法之外的数据

时间:2017-05-19 10:55:08

标签: javascript angular typescript promise ionic2

我正在学习Ionic 2.我已将一些数据存储在 SomeComponent 中的离子本地存储中,并在 UserService 中重新获取相同数据调用后端,但storage.get()方法返回承诺,所以当我了解承诺时,我无法获取数据。任何人都可以帮助我更好地完成这项工作吗?谢谢,如果有的话。

这是我的代码。

export class SomeComponent {

 user: User;
 usename: string;
 password: string;

   constructor(
    public navParams: NavParams,
    public navController: NavController, 
    public loginService: LoginSevice,
    public storage: Storage) {

   }

    login() {
        this.loginService.login(this.username, this.password).subscribe( response => {
          this.user = response;
          this.storage.set('userId', this.user.userId);
          this.storage.set( 'authcode', this.user.authCode);
        });
      }
}

服务是

    export class UserService {

      userId: string;
      constructor(public http: Http, public storage: Storage){}

      fetchUserInfo(): Observable<User> { 

          this.storage.get('userId').then((val) => {
            console.log(val); // available only inside then() method
            this.userId = val; 
          });

          let user = btoa(this.userId); // userId is undefined
          return this.http.get(`${this.baseUrl}/user/${user}/details`, {headers: 
               this.headers})
             .map(res =>res.json());
         }
      }
   }

2 个答案:

答案 0 :(得分:2)

解决这种情况的一种方法是:

export class UserService {

    userId: string;
    constructor(public http: Http, public storage: Storage){}

    fetchUserInfo(): Observable<User> { 

        return Observable
            .fromPromise(this.storage.get('userId'))
            .flatMap(userId => 
                this.userId = val;

                let user = btoa(this.userId);
                return this.http.get(`${this.baseUrl}/user/${user}/details`, {headers: this.headers})
                           .map(res =>res.json());
    }
}

这样,我们首先创建一个带有promise的observable,它将从存储返回值userId,然后使用userId我们正在制作http请求(将返回Observable<User>)。您可以找到有关flatmap运算符here的更多信息。

答案 1 :(得分:0)

我试过mergeMAp这也很有效。我不知道同时使用flatMapmergMap的区别,但它有效。

export class UserService {
    userId: string;
    constructor(public http: Http, public storage: Storage){}
    fetchUserInfo(): Observable<User> { 
    return Observable
          .fromPromise(this.storage.get('userId')).mergeMap(userId => 
              this.userId = val;
              let user = btoa(this.userId);
              return this.http.get(`${this.baseUrl}/user/${user}/details`, {headers: this.headers})
                               .map(res =>res.json());
    }
}