Angular如何将*ngFor与Async管道一起使用



嗨,我在使用异步ngFor时遇到了问题。我有一个最简单的例子,一个从服务器onInit获得的对象数组,我想在int到达后对其进行迭代,这就是我在模板上写它的方式:

<p *ngFor="let msg of messages | async">test</p> 

我的意思是,它在我看来还可以,但显然不是,这是ts部分:

export class ChatComponent implements OnInit {
url = 'http://localhost:8080';
otherUser?: User;
thisUser: User = JSON.parse(sessionStorage.getItem('user')!);
channelName?: string;
socket?: WebSocket;
stompClient?: Stomp.Client;
newMessage = new FormControl('');
messages?: Observable<Array<Messaggio>>;
constructor(
private route: ActivatedRoute,
private userService: UserService,
private http:HttpClient
) {}
ngOnInit(): void {
this.userService
.getUserByNickname(this.route.snapshot.paramMap.get('user')!)
.subscribe((data) => {
this.otherUser = data;
this.otherUser.propic = "data:image/jpeg;base64,"+ this.otherUser.propic;
this.connectToChat();
});
}
connectToChat() {
const id1 = this.thisUser.id!;
const nick1 = this.thisUser.nickname;
const id2 = this.otherUser?.id!;
const nick2 = this.otherUser?.nickname!;
if (id1 > id2) {
this.channelName = nick1 + '&' + nick2;
} else {
this.channelName = nick2 + '&' + nick1;
}
this.loadChat();
console.log('connecting to chat...');
this.socket = new SockJS(this.url + '/chat');
this.stompClient = Stomp.over(this.socket);
this.stompClient.connect({}, (frame) => {
//func = what to do when connection is established
console.log('connected to: ' + frame);
this.stompClient!.subscribe(
'/topic/messages/' + this.channelName,
(response) => {
//func = what to do when client receives data (messages)
let data:Messaggio = JSON.parse(response.body);
console.log(data);
//this.messages.push(data);
//this.messages = this.messages.slice();
}
);
});
}

loadChat(){
let messages: Array<Messaggio>;
this.http.post<Array<Messaggio>>(this.url+'/getMessages' ,  this.channelName).subscribe(data =>{
messages = data;
console.log(messages);
})
}

关于这个问题的部分是loadChat方法,它是在onInit中调用的方法中调用的,所以基本上它是在on-init和数组的声明中调用的

重点是数组已经定义好了,我甚至把它打印在控制台上,但html页面不做jack

确保您的消息对象是类型的Observable。和在使用ng循环之前添加一个null检查。如果一旦您的消息可观察到有一些数据,下面的代码将正常工作

<div *ngIf="(messages | async)">
<p *ngFor="let msg of messages | async">test</p> 
</div>

感谢那些仍然在回答这个问题的人,但我从第一条评论就解决了,问题是:我很愚蠢,我把服务器上的数据分配给了方法的本地数组,而不是组件的属性,如果我这样做了,它从开始就可以工作了

lmao

最新更新