Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

angular - Ionic2 - setting and retrieving the value of storage fails

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...