【问题标题】:How I can fix the problem with send-message method?如何解决发送消息方法的问题?
【发布时间】:2020-05-29 00:22:03
【问题描述】:

我在编译代码时遇到了一个问题。我必须编写能够进行聊天的 Web 应用程序。现在,我编写了 chat.service,但是我遇到了问题。为什么?请帮我。我发送聊天服务的照片。在此处输入图像描述。 enter image description here

{ 类型参数 '{ message: string;时间发送:字符串;用户名:可观察的;电子邮件:任何; }' 不可分配给“ChatMessage[]”类型的参数。}

也发送我的代码:

@Injectable()
export class ChatService {
  user: any;
  chatMessages: AngularFireList<ChatMessage[]>;
  chatMessage: ChatMessage;
  userName: Observable<string>;

  constructor(
    // create value for angularFirebase
    private db: AngularFireDatabase,
    private afAuth: AngularFireAuth
  ) {
      this.afAuth.authState.subscribe(auth => { // check the auth user message
        if (auth !== undefined && auth !== null) {
          this.user = auth;
        }
      });
    }
// send message method with get time and get back message
  sendMessage(message: string) {
    const timestamp = this.getTimeStamp();
    const email = this.user.email;
    this.chatMessages = this.getMessages();
    this.chatMessages.push({
      message: message,
      timeSent: timestamp,
      userName: this.userName,
      email: email,
    });
  }

  getMessages(): AngularFireList<ChatMessage[]> {
    return this.db.list('message', ref => ref.orderByKey().limitToLast(25));
  }

  private getTimeStamp() {
    const now = new Date();
    const date = now.getUTCFullYear() + '/' + (now.getUTCMonth() + 1) + '/' + now.getUTCDate();
    const time = now.getUTCHours() + ':' + now.getUTCMinutes() + ':' + now.getUTCSeconds();

    return (date + ' ' + time);

   }
}

【问题讨论】:

  • ChatMessage 界面是什么样的?
  • 我附上了我的代码照片
  • 代码图片没有帮助。它们不能被复制来尝试或理解。对于某些设备,它们可能无法很好地呈现,并且无法重新设置样式以处理用户可访问性。请在您的问题中包含代码并使用格式。
  • 我也发布了我的代码。谢谢

标签: javascript angular firebase firebase-realtime-database angularfire2


【解决方案1】:

问题来自这个代码片段:

this.chatMessages = this.getMessages();
this.chatMessages.push({
  message: message,
  timeSent: timestamp,
  userName: this.userName,
  email: email,
});

在第一行中,您将chatMessages 初始化为AngularFireList&lt;ChatMessage[]&gt;,这是由AngularFire2 定义的类型。然后在下一行中,您尝试 push 为该类型添加一个新项目,这不是一个有效的操作,因为该对象似乎不是一个有效的 ChatMessage。您需要确保您传递的 JSON 对于ChatMessage 是正确的,或者实际创建一个ChatMessage 对象并将其推送到chatMessages

【讨论】:

    【解决方案2】:

    您似乎正在将一个对象传递给一个需要数组的函数。 从提供的小 sn-p 来看,您可以将数据包装到仅包含该元素的数组中。 可能能够使代码正常工作。 请查看@kurt-hamilton 的建议并改进您的问题

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 2019-06-29
      • 2022-08-13
      • 2021-08-05
      • 2016-01-13
      • 2021-06-05
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多