我有一个名为聊天的模型,就像这样:
export class Chat {
chatId?: number;
chatUser1?: string;
chatUser2?: string;
chatStatus?: string;
created_at?: any;
updated_at?: any;
deleted_at?: any;
}
在组件中,我想找到具有特定值的 chatUser2 ,因此,我为此模型声明了一个名为 chats 的数组。
chats:Chat[];
然后,我得到了这个功能:
getChats(): void {
this.loadingChats = true;
this.chatService.getChats().subscribe((data: any[]) => {
this.chats = data;
});
this.toCall=true;
this.toAnswer=false;
this.toHangUp=false;
var status="true";
var chatUser2 = [];
var chatStatus = [];
var chatChannel = [];
chatUser2 = this.chats.map((v)=>v.chatUser2);
chatStatus = this.chats.map((v)=>v.chatStatus);
chatChannel = this.chats.map((v)=>v.chatId.toString());
var size = chatUser2.length;
for(var i=0; i<size ; i++)
{
console.log(i.toString());
if(chatUser2[i] === this.userName && chatStatus[i]===status)
{
this.toAnswer=true;
this.toCall=false;
this.toHangUp=false;
this.channel=chatChannel[i];
console.log("break");
break;
}
}
但是控制台显示此错误 ERROR TypeError:“
中的“ this.chats未定义”chatUser2 = this.chats.map((v)=>v.chatUser2);
非常感谢。
答案 0 :(得分:1)
此chatService.getChats()
(可观察)是一个异步操作,您需要等待它完成,这是使用async / await解决此问题的一种方式
async getChats() : Promise<void> {
this.loadingChats = true;
this.chats = await this.chatService.getChats().toPromise();
this.toCall=true;
this.toAnswer=false;
this.toHangUp=false;
var status="true";
var chatUser2 = [];
var chatStatus = [];
var chatChannel = [];
chatUser2 = this.chats.map((v)=>v.chatUser2);
chatStatus = this.chats.map((v)=>v.chatStatus);
chatChannel = this.chats.map((v)=>v.chatId.toString());
var size = chatUser2.length;
for(var i=0; i<size ; i++)
{
console.log(i.toString());
if(chatUser2[i] === this.userName && chatStatus[i]===status)
{
this.toAnswer=true;
this.toCall=false;
this.toHangUp=false;
this.channel=chatChannel[i];
console.log("break");
break;
}
}
另一个选择是将您的代码移到订阅方法的正文中
getChats(): void {
this.loadingChats = true;
this.chatService.getChats().subscribe((data: any[]) => {
this.chats = data;
// ....
});
}