Angular 5 Firebase推送对象" new"关键词vs对象文字

时间:2018-03-08 07:27:45

标签: angular firebase

将数据发送到firebase数据库时。我首先尝试推送由" new"创建的对象。关键词:

addPost(value: string){
    this.postList.push(new PostObject(value, false));
}

无法在数据库中看到该对象。但是当我尝试使用对象文字时,它起作用了:

addPost(value: string){
    this.postList.push({
      text: value,
      isLiked: false
    });
}

PostObject类:

export class PostObject {

    comment = [];

    constructor(text: string, isLiked: boolean){}

}

那么上面两种方法有什么区别?有没有办法可以使用构造函数创建对象并将对象发送到数据库?

1 个答案:

答案 0 :(得分:0)

是。

但你仍然可以使用"快捷方式"语法,如果您使用公共或私人关键字。我在打字稿操场上做了一些测试,它工作得很好!

看看:

https://www.typescriptlang.org/play/index.html#src=class%20PostObject%20%7B%0D%0A%0D%0A%20%20%20%20comment%20%3D%20%5B%5D%3B%0D%0A%0D%0A%20%20%20%20constructor(private%20text%3A%20string%2C%20private%20isLiked%3A%20boolean)%7B%7D%0D%0A%0D%0A%7D%0D%0A%0D%0Alet%20post%20%3D%20new%20PostObject(%22Test%22%2Ctrue)%3B%0D%0A%0D%0Alet%20button%20%3D%20document.createElement('button')%3B%0D%0Abutton.textContent%20%3D%20%22Post%22%3B%0D%0Abutton.onclick%20%3D%20function()%20%7B%0D%0A%20%20%20%20console.log(JSON.stringify(post))%3B%0D%0A%7D%0D%0A%0D%0Adocument.body.appendChild(button)%3B
相关问题