我的组件中有以下代码,而ionViewDidLoad方法中的chats.push()函数会生成错误:
@Component({
selector: 'page-messages',
templateUrl: 'messages.html'
})
export class MessagesPage {
currentUser: User;
chats: Chat[];
constructor(public navCtrl: NavController, public navParams: NavParams, private _auth: AuthService, private _db: DatabaseService, private _user: UserService) {
console.log('constructor MessagesPage');
// Get currently authenticated user
this.currentUser = this._auth.currentUser;
}
ionViewDidLoad() {
//console.log(this.chats.length);
console.log('ionViewDidLoad MessagesPage');
// Load chats
this._user.getChatsAsObservableList(this.currentUser.uid).subscribe(tmpChats => {
tmpChats.forEach(tmpChat => {
console.log(tmpChat);
// Retrieve chat id
let chatId = tmpChat.$key;
console.log('Retrieving a chat with id ', chatId);
// Instantiate a Chat object
let chat = new Chat(chatId, tmpChat);
// Retrieve its members
let chatMembers = this._db.getChatMembersAsObservableList(chatId);
// For each member retrieve the user info and add it the members of the Chat object
chatMembers.subscribe(members => {
members.forEach(member => {
this.addMemberToChat(chatId, member.$key);
});
});
// finally add the chat to the chat list
this.chats.push(chat); // Generates an ERROR : Cannot read property 'push' of undefined
console.log('Chat:', chat);
});
});
}
// Methods
addMemberToChat(chat: Chat, uid: string) {
if (uid) {
let userAsObservableObj = this._user.getUserAsObservableObj(uid);
let user = new User(uid, userAsObservableObj);
chat.members.push(user);
} else {
console.log('Could not add member to Chat object because uid was empty.');
}
}
}
我想这是一个"这个"问题,我看到很多关于这个的帖子,但我无法用胖箭解决它。我想这是因为我有几个承诺......
我怎么解决这个问题?
答案 0 :(得分:1)
初始化聊天解决了这个问题:
chats: Chat[] = [];