Ionic2 - setting and retrieving the value of stora

2019-09-21 06:49发布

问题:

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.

回答1:

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/