我正在研究如何在YouTube视频系列之后创建Angular Firebase聊天:https://www.youtube.com/watch?v=-j0LVc-zLh0
在这里,我正在使用聊天服务(chat.service.ts),如下所示:
import {
Injectable
} from '@angular/core';
import {
AngularFireList, AngularFireDatabase
} from 'angularfire2/database';
import {
AngularFireAuth
} from 'angularfire2/auth';
import {
Observable
} from 'rxjs/Observable';
import {
ChatMessage
} from '../models/chat-message.model';
import {
AuthService
} from '../services/auth.service';
import * as firebase from 'firebase/app';
@Injectable()
export class ChatService {
user: any;
chatMessages: AngularFireList < ChatMessage[]> ;
chatMessage: ChatMessage;
userName: Observable<string>;
constructor(
private db: AngularFireDatabase,
private angularFireAuth: AngularFireAuth
) {
// this.angularFireAuth.authState.subscribe(auth => {
// if (auth !== undefined && auth !== null) {
// this.user = auth;
// }
// })
}
sendMessage(msg: string) {
const timestamp = this.getTimestamp();
// const email = this.user.email;
const email = "ex@ex.com";
this.chatMessages = this.getMessages();
this.chatMessages.push({
message: msg,
timeSent: timestamp,
userName: this.userName,
email: email
});
}
getMessages(): AngularFireList<ChatMessage[]> {
return this.db.list('messages', ref => ref.orderByKey().limitToLast(25)
// console.log("test ok")
)};
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);
}
}
在sendMessage函数中,当我尝试将消息输入ChatMessages []时,message: msg
行被标记为错误,我在终端中收到以下错误消息。
src / app / services / chat.service.ts(48,4)中的错误:错误TS2345: 类型的参数&#39; {message:string; timeSent:string;用户名: 观察到;电子邮件:string; }&#39;不能分配给参数 类型&#39; ChatMessage []&#39;。对象文字可能只指定已知 属性和&#39;消息&#39;类型&#39; ChatMessage []&#39;。
中不存在
有人可以帮我这个吗?
答案 0 :(得分:1)
ChatMessage之后你不需要括号。
getMessages(): AngularFireList<ChatMessage> {
return this.db.list('messages', ref => ref.orderByKey().limitToLast(25)
// console.log("test ok")
)};
如果在此之后它仍然无效,那么在推送之前订阅您的用户名。
this.chatMessages.push({
message: msg,
timeSent: timestamp,
userName: this.userName,----subscribe it
email: email
});