0

我定义了一个打字稿类,如下所示:

export class UserModel{
    private _name:string
    private _email:string
    private _userId:string
    private _teamId:string
    private _avatar:string
    private _teamName:string

    constructor(name:string, email:string, userId:string, teamId:string, avatar:string, teamName:string){
        this._name = name
        this._email = email
        this._userId = userId
        this._teamId = teamId
        this._avatar = avatar
        this._teamName = teamName
    }

    get name():string{
        return this._name
    }

    set name(val:string){
        this._name = val
    }

    get email():string{
        return this._email
    }

    set email(val:string){
        this._email = val
    }

    get userId():string{
        return this._userId
    }

    set userId(val:string){
        this._userId = val
    }

    get teamId():string{
        return this._teamId
    }

    set teamId(val:string){
        this._teamId = val
    }

    get avatar():string{
        return this._avatar
    }

    set avatar(val:string){
        this._avatar = val
    }

    get teamName():string{
        return this._teamName
    }
}

字段被设为私有并使用 getter 和 setter 访问。这很好用,除了当我将对象存储到 firebase db 时,它将它与 _ 一起存储

{
"_name":"vik,
"_email": "blas@gmal.com"
...
}

这会破坏我的整体代码,因为当我下次渲染它时,我的属性名称现在从名称更改为 _name。

有没有一种方法,当我将这个对象持久保存到 firebase 时,它​​会在没有 _ 的情况下存储它

请指教

4

2 回答 2

0

我可能会在 TypeScript 地狱中遭受漫长而痛苦的死亡,但这是我在保存到 Firestore 之前从类实例递归创建对象的方法。我告诉自己,对这个——而且只有这个——TypeScript 方法马虎是可以的,因为无论如何它是离开 TypeScript 世界之前的最后一步。

核心方法:

function toObjectRecursive (a: {[key: string]: any}) : object {
  a = Object.assign({}, a);

  const keys = Object.keys(a);

  const okObjectConstructorNames = [
    "function Array() { [native code] }",
    "function Object() { [native code] }"
  ]

  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    const val = getProperty(a, key)
    const typename = typeof val;
    const constructor = val !== undefined && val !== null ? val.constructor.toString() : "";

    if (typename === "object" && okObjectConstructorNames.indexOf(constructor) === -1) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      setProperty(a, key, toObjectRecursive(a[key]))
    }
  }

  return a;
}

你还需要两个助手(我会更新引用)

export function getProperty<T, K extends keyof T> (o: T, propertyName: string): T[K] {
  return (o[propertyName as K]); // o[propertyName] is of type T[K]
}

export function setProperty<T, K extends keyof T> (o: T, propertyName: string, val: T[K]) {
  o[propertyName as K] = val; // o[propertyName] is of type T[K]
}
于 2021-03-06T17:19:56.790 回答
0

您必须编写代码将所有对象值映射到具有要存储在数据库中的确切字段名称的对象中。Firebase SDK 没有为此提供任何捷径,除了您编写的内容以使其变得简单。

于 2018-07-13T06:34:16.893 回答