Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am setting the value of storage in ionic. But, I am unable to retrieve it.

This is what I have done

In my login service

@Injectable()
export class Authservice {
  storage: Storage;

  login(user: UserModel): Observable<any> {
  return this._http.post(this.loginurl + "mobile-login", body)
     .map((response: Response) => {
     let token = response.json().access_token;
     if (token) {
         console.log(token) //this returns a value of the token
       this.storage.set('token', token);

      this.storage.get('token').then((val) => {
        console.log("token value now is"+val);  //this returns nothing
      })
    } else {
      // return false to indicate failed login
      return false;
    }
    })
    //.catch(this.handleError);
 }

Also in another service I've tried

   this._storage.get('token')
  .then(res=>{
      console.log("in the other area token is"+res)//this is null

    }
  );

I've tried retrieving the value in a constructor like this

authtoken:string;

  constructor(private http: Http, private _storage:Storage) {
this._storage.get('token')
  .then(res=>{
        this.authtoken= res;

    }
  );
  }

Then in the component I've tried

console.log(this.authtoken)  //still nothing

In my app module I've also added

providers[Storage]

What could be the problem. I am testing on chrome browser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

This because the storage.set returns a promise, it's not a synchronous process.

So, when you call storage.get immediately, the token has not yet been fully saved to storage, and you get nothing.

You can create a public event, when the storage set is successful.

import { BehaviourSubject, Subject } from 'rxjs';

tokenEvent: Subject = new BehaviourSubject(null);

...

this.storage.set('token', token).then(res => this.tokenEvent.next(true));

In other component:

constructor(private auth: Authservice){}
ngOnInit() {
  this.auth.tokenEvent.subscribe(res => {
    if (res) {
      this.this.storage.get('token')
        .then(token => console.log(token));
    }
  })
}

API document: https://ionicframework.com/docs/v2/storage/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...