【问题标题】:Object literal may only specify known properties and 'message' does not exist in type 'ChatMessage[]'对象文字只能指定已知属性,并且“ChatMessage[]”类型中不存在“消息”
【发布时间】:2017-11-28 22:40:27
【问题描述】:

我在 sendMessage 函数中的 chat.services.ts 中遇到错误。 我正在尝试做一个异步管道,但它没有从我的 chat-message.model.ts 中读取对象

这是我在 chat-message.model.ts 中的代码:

export class ChatMessage {
$key?: string;
email?: string;
userName?: string;
message?: string;
timeSent?: Date = new Date();
 }

这也是我在 chat.services.ts 中的代码:

sendMessage(msg: string){
const timestamp = this.getTimeStamp();
const email = 'test@example.com';
this.chatMessages = this.getMessage();
this.chatMessages.push({
  message: msg,
  timeSent: timestamp,
  userName: 'test-user',
  email: email });

    getMessage(): AngularFireList<ChatMessage[]> {
    // Query to create  Message Feed Binding
    console.log('Calling getMessages()!')
    return this.db.list('messages')

}  

我觉得这很明显,但代码在我看来确实不错。

我感觉这可能与 $key 有关?

【问题讨论】:

  • getMessages 长什么样子?
  • 编辑了问题,getMessages() 工作正常,就像我在通过我的 firebase 数据库之前发送消息时一样

标签: angular typescript


【解决方案1】:

这是您的代码的简短版本,它解释了我希望在哪里看到错误。首先,这是一段演示代码:

export class ChatMessage {
    $key?: string;
    email?: string;
    userName?: string;
    message?: string;
    timeSent?: Date = new Date();
}

const chatMessages: ChatMessage[] = [];

chatMessages.push({
    message: 'Message',
    timeSent: new Date(),
    userName: 'test-user',
    email: 'fenton@example.com'
});

你得到的错误说:

“聊天消息[]”类型中不存在“消息”

这很有趣...这意味着它认为chatMessages: ChatMessage[] 看起来更像ChatMessage[][](即包含聊天消息数组的数组)。

因此,通过将错误移至带有注释的有趣行来测试理论:

this.chatMessages: ChatMessage[] = this.getMessage();

我预计这一行会有错误,因为this.getMessage();返回的类型不是ChatMessage[]

如果还是卡住,请给我们getMessage()方法。

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 2021-09-27
    • 2019-08-13
    • 2019-12-03
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多