Ionic 2/Angular 2 promise returning observable

后端 未结 4 1430
-上瘾入骨i
-上瘾入骨i 2021-02-15 02:46

I have a situation where I need to fetch a piece of data from storage in an Ionic 2 application and then use that data to create an HTTP request. The problem that I am running i

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-15 03:13

    Here's what you can do:

    Your code below

     getToken() {
        return this.storage.get('token').then((token) => {
            this.token = token;
            return token;
        });
     }
    

    changes to

    getToken: Observable = 
        Observable.fromPromise(this.storage.get('token').then(token => {
        //maybe some processing logic like JSON.parse(token)
        return token;
    }));
    

    Then in your component you can consume it like would any other observable.

    this.serviceClass.getToken.subscribe(token => { 
    //whatever you want to with the token
    });
    

提交回复
热议问题