【问题标题】:Getting ZoneAwarePromise from Firebase snapshot value从 Firebase 快照值获取 ZoneAwarePromise
【发布时间】:2016-11-15 15:49:18
【问题描述】:


在我的组件中,我正在从服务提供商调用一个函数。 从 Firebase 调用 get 函数,我在控制台中得到的是 ZoneAwarePromise。我做错了什么?

在xx.component.ts 文件中:

constructor( private db: Database ) {

    console.log(db.getActiveUserData());

}

database.ts文件:

getActiveUserData(){
    return this.database.child('/users/' + this.as.id).once('value').then((snapshot) => {
        return snapshot.val();
    })
}

控制台日志:

ZoneAwarePromise __zone_symbol__state:true

__zone_symbol__值 : 目的 名 : 弗雷德里克 uid : "zLmRHwQRM0cehsSrGNXaH2WnSgk2"

原型 : 目的 原型 : 对象

如何将数据作为普通对象接收?

当我在database.ts 中使用控制台日志时,一切正常

【问题讨论】:

  • 你不能将实时的异步操作变成同步的返回值。您需要异步使用它们,传递承诺,然后等待它解决(将您的 console.log() 放在 .then() 中,例如 db.getActiveUserData().then(console.log)

标签: angular firebase firebase-realtime-database


【解决方案1】:

您看到的是预期的行为。

once 返回一个承诺,这就是 getActiveUserData 返回的内容。您不能让它返回快照的值。但是,您可以获得返回的 Promise 以解析为快照的值:

getActiveUserData() {

  return this.database
    .child('/users/' + this.as.id)
    .once('value')
    .then((snapshot) => snapshot.val());
}

你会这样称呼:

@Component({
    selector: "some-component",
    template: `<code>{{ activeUserData | json }}</code>`
})
class SomeComponent {

  activeUserData: any;

  constructor( private db: Database ) {

    db.getActiveUserData().then((val) => { this.activeUserData = val; });
  }
}

Angular 模板理解 Promise,因此数据可以作为 Promise 保存,并且可以使用 async 管道:

@Component({
    selector: "some-component",
    template: `<code>{{ activeUserData | async | json }}</code>`
})
class SomeComponent {

  activeUserData: Promise<any>;

  constructor( private db: Database ) {

    this.activeUserData = db.getActiveUserData();
  }
}

【讨论】:

  • 这有帮助!但是如何将“ val ”设置为变量?像 this.activeuser = val.
  • 我已经更新了答案。但是,您可能想了解更多关于 Promise 的信息;有很多可用的材料:promisejs.org, JavaScript Promises: an Introduction
猜你喜欢
  • 2019-06-14
  • 2018-09-26
  • 2018-07-10
  • 2018-01-21
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多