user1139675
user1139675

Reputation: 454

nativeStorage in ionic 2 and providers

I want to store a token in local storage, and if it exists tweak it slightly and then use it on the page.

With ionic 1 it was easy to create a service that just got the data from local storage, changed it and returned it so the main component can do with it as it will.

however now that NativeStorage.getItem() returns a promise, how do i force the service to fully complete getting the item, and finishing my other changes before returning the tweaked token as the data?

I want to be able to do:

export class Test{
    let tok = "";
    constructor(tokenService:TokenService){
       this.tok = tokenService.getToken()
    }

    ngOnInit(){
      alert(this.tok + " Is your token");
    }
}

and in tokenService the provider have:

getToken(){
// this doesn't work now because it will return undef for modified_token not waiting for the promise to finish
    let modified_token:string; 
    NativeStorage.getItem('token').then(
        data=>{ 
            modified_token = data + 'modified'; 
        }
    ); 
    return modified_token
}

Do i just have to have another main function that is called when the promise is finished?

like:

getToken(){
    return NativeStorage.getItem('token')
}

and instead of in the constructor in ngOnInit have:

ngOnInit(){
 tokenService.getToken().then(
    data => { 
        let modified_token = data + "modified";
        mainAction(modified_token);
    })
}

and mainAction() has the rest of what i want to do?

Upvotes: 1

Views: 1489

Answers (1)

sebaferreras
sebaferreras

Reputation: 44669

Do i just have to have another main function that is called when the promise is finished?

That's one way to do it. You could also keep all the related logic inside the getToken method by returning a new Promise like this:

getToken(){
   return NativeStorage.getItem('token').then(data => return data + 'modified')
}

And then

ngOnInit(){
 tokenService.getToken().then(
    modifiedToken => { 
        mainAction(modifiedToken);
    })
}

UPDATE: the answer was updated according to @SamMason comment.

Upvotes: 2

Related Questions