首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待来自订阅的异步数据

如何等待来自订阅的异步数据
EN

Stack Overflow用户
提问于 2018-09-10 00:58:31
回答 1查看 238关注 0票数 0

因此,我正在尝试等待订阅来自本地存储服务的数据,但我从本地存储获得的数据有时会延迟,并且未定义.Uid

代码语言:javascript
复制
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变量呢?

EN

回答 1

Stack Overflow用户

发布于 2018-09-10 01:10:39

您不能等待subscribe方法。如果你还使用了wait方法,那么当你第一次加载你的页面时,订阅会自动调用,直到你的API没有被调用,你才会得到始终为null的值。

如果你得到的id是subscribe,那么就在undefined中使用if(data)

本例中的示例:

代码语言:javascript
复制
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();
    }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52246738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档