Ionic 2/Angular 2 promise returning observable

后端 未结 4 1417
-上瘾入骨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:04

    I got it to work using a combination of Observable.fromPromise() and .flatMap():

    getToken() {
        return Observable.fromPromise(this.storage.get('token')
        .then((token) => {
            return token;
        }));
    }
    
    loadStuff(){
        return this.tokenService.getToken()
        .flatMap(token => {
            return this.http.get("https://www.urltodatasource.com/api/v1/Endpoint?access_token="+token)
            .map(res => {
                return res.json();
            });
        });
    }
    
    this.tokenService.loadStuff().subscribe(data => {
        this.storage.set('stuff', data);
        return data;
    });
    

    You'll also need to add these imports:

    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/observable/fromPromise';
    import 'rxjs/add/operator/mergeMap';
    

提交回复
热议问题