因此,我正在尝试等待订阅来自本地存储服务的数据,但我从本地存储获得的数据有时会延迟,并且未定义.Uid
constructor(private route: ActivatedRoute,
private cp: CommerceProvider,
protected localStorage: LocalStorage) {
this.localStorage.getItem('castra').subscribe((data) => {
this.uid = data.uid;
console.log(data);
this.getCastraProfile();
})
}
ngOnInit() {
let id = parseInt(this.route.snapshot.paramMap.get('id'));
this.castra_id = id;
this.localStorage.getItem('cart').subscribe((cart) => {
if(cart.length == 0){
this.localStorage.setItem('castra', { 'uid': this.castra_id
}).subscribe(() => {});
}
}, (error)=> {
this.localStorage.setItem('cart', []).subscribe(() => {});
});
}那么,如何等待这些数据到来,然后将其赋给uid变量呢?
发布于 2018-09-10 01:10:39
您不能等待subscribe方法。如果你还使用了wait方法,那么当你第一次加载你的页面时,订阅会自动调用,直到你的API没有被调用,你才会得到始终为null的值。
如果你得到的id是subscribe,那么就在undefined中使用if(data)。
本例中的示例:
this.localStorage.getItem('castra').subscribe((data) => {
if(data){
// This will call if they have some data. It call if data have 'null' or 'Undefined' value.
this.uid = data.uid;
console.log(data);
this.getCastraProfile();
}
});https://stackoverflow.com/questions/52246738
复制相似问题