嗨,我在使用異步 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);
})
}
關于問題的部分是在onInit中呼叫的方法中呼叫的loadChat方法,所以基本上它在on init中呼叫,以及陣列的宣告
點是陣列被定義我什至在控制臺上列印它但html頁面不做jack
uj5u.com熱心網友回復:
確保您的訊息物件是Observable 型別。并在使用ngIf回圈之前添加一個空檢查, 一旦您的訊息 observable 有一些資料,下面的代碼就可以正常作業
<div *ngIf="(messages | async)">
<p *ngFor="let msg of messages | async">test</p>
</div>
uj5u.com熱心網友回復:
感謝那些仍在回答這個問題的人,但我從第一條評論中解決了這個問題,問題是:我很愚蠢,我將來自服務器的資料分配給方法本地的陣列而不是組件的屬性,如果我這樣做從一開始就行得通
毛
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372379.html
