将 Typescript 类型同步到 Firebase Object Observables 而不会丢失功能等

Syncing Typescript types to Firebase Object Observables without losing functions etc

我正在使用 Typescript 开发一个 Angular 2 应用程序,我经常遇到这样一个问题,即在同步数据时我似乎无法很容易地持久化对象类型。

我一直在手动设置属性。在某些情况下,我只是删除 $exists()、$key、c​​reatedat 函数和属性以便能够更新数据。

有没有办法从 Firebase 对象设置 class 而无需完全更改它?

举个例子:

search$:FirebaseObjectObservable<ISearchQuery>;
search:ISearchQuery;

constructor(public af: AngularFire, public auth: AuthService){
  this.search$ = this.af.database.object(`/queries/saved/${auth.id}`);
  //THIS IS HOW I WANT TO DO IT
  this.search$.subscribe((data)=>{
    if(data.$exists()){
       this.search=data;           
    }
  });  

  //THIS IS WHAT I'VE RESORTED TO
  this.search$.subscribe((data)=>{
    if(data.$exists()){
      this.search.categories = data.categories;
      this.search.creators = data.creators;
      this.search.endDate = data.endDate;
      this.search.startDate = data.startDate;
      this.search.location = data.location;
     }
  });  
}

另一方面,当我同步和更新数据后,我必须在更新或设置为 firebase 时选择每个 属性。如果我直接同步,我也会 运行 遇到问题我也会丢失 class 函数(因为 firebase 对象在原型中有自己的一组函数)。

有没有办法避免通过 属性 选择 属性 或者有更好的方法来处理 Firebase 对象与 Typescript 的同步?

听起来您希望 AngularFire2 保留 Firebase 快照。默认情况下,它 'unwraps' the snapshots,添加 $ 前缀 属性 和您不需要的函数。

如果您指定 preserveSnapshot 选项,它不会执行此操作,您可以调用 snapshot.val():

constructor(public af: AngularFire, public auth: AuthService) {

  this.search$ = this.af.database.object(`/queries/saved/${auth.id}`, {
    preserveSnapshot: true
  });
  this.search$.subscribe((snapshot) => {
    if(snapshot.exists()) {
       this.search = snapshot.val();
    }
  });
}

如果您以后需要它,您可以随时保留快照。

关于 ISearchQuery - 我假设它是一个接口 - 您从 snapshot.val() 收到的值是一个匿名对象。将其转换为描述数据 'shape' 的接口是安全的,但如果该接口包含方法,则它不会起作用,因为这些方法将不存在于匿名对象上。如果您有一个实现该接口的 class,您应该包含一个构造函数,该构造函数接受您从 snapshot.val().

收到的匿名对象

例如:

this.search$.subscribe((snapshot) => {
  if(snapshot.exists()) {
    // Given SomeSearchQuery implements ISearchQuery
     this.search = new SomeSearchQuery(snapshot.val());
  }
});