Ionic2 - 设置和检索存储的值失败 [英] 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.
这就是我所做的事情
在我的登录服务中
@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;
}
);
}
然后在组件中我试过了
console.log(this.authtoken) //still nothing
在我的应用模块中,我还添加了
In my app module I've also added
providers[Storage]
可能是什么问题。我在chrome浏览器上测试。
What could be the problem. I am testing on chrome browser.
推荐答案
这是因为 storage.set
返回一个承诺,这不是一个同步过程。
This because the storage.set
returns a promise, it's not a synchronous process.
所以,当你立即调用 storage.get
时,令牌尚未完全保存到存储空间,您什么也得不到。
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));
在其他组成部分:
constructor(private auth: Authservice){}
ngOnInit() {
this.auth.tokenEvent.subscribe(res => {
if (res) {
this.this.storage.get('token')
.then(token => console.log(token));
}
})
}
API文件: https://ionicframework.com/docs/v2/storage/
这篇关于Ionic2 - 设置和检索存储的值失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!