AngularFireList推送错误:类型的参数' {message:string; }'不能分配给' ChatMessage []'

时间:2018-04-07 09:11:27

标签: angular angular5 angularfire

这是我的ChatMessage模型:

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

这是我的AngularFireList代码:

chatMessages: AngularFireList<ChatMessage[]>;

const timestamp = this.getTimeStamp();
    //const email = this.user.email;
    const email = "example@abc.com";


this.chatMessages.push({
  message: msg,
  timeSent: timestamp,
  email: email,
  //userName: this.userName,
  userName: "user-test",


});

 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);              
  }

我有一个错误说:

  

消息:&#39;类型的参数&#39; {message:string; timeSent:string;电子邮件:string; userName:string; }&#39;不能分配给&#39; ChatMessage []&#39;类型的参数。     对象文字只能指定已知属性,并且&#39; message&#39;类型&#39; ChatMessage []&#39;。

中不存在

4 个答案:

答案 0 :(得分:1)

问题在于您的getTimeStamp()功能,该功能会返回string,而不是Date

因此,当你这样做时

this.chatMessages.push({
  message: msg,
  timeSent: timestamp,
  email: email,
  userName: "user-test",
});

您尝试推送的对象并不满足界面。您可以修改界面以使用timeSent类型字符串,也可以修改getTimeStamp函数以返回Date

答案 1 :(得分:0)

this.chatMessages.push(
  [
    {
      message: '',
      timeSent: timestamp,
      email: '',
      // userName: this.userName,
      userName: 'user-test',
    }
  ]
);

chatMessages: AngularFireList<ChatMessage[]>;

替换为

chatMessages: AngularFireList<ChatMessage>;

答案 2 :(得分:0)

更正:请注意,In []: %timeit updown_orig(np.random.rand(200, 50)) 96.4 ms ± 1.91 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In []: %timeit updown(np.random.rand(200, 50)) 5.84 ms ± 64 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 要求数组的单个元素的类型。

请勿在{{1​​}}中AngularFireList后面放置[]括号。

答案 3 :(得分:0)

我遇到了同样的问题,而是尝试了一下(效果很好):

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

const time = now.getUTCHours() + ':' +
  now.getUTCMinutes() + ':' +
  now.getUTCSeconds();
return now;

希望这对您或其他任何人都很有价值。顺便说一句,它在Angular版本10.X中;)