簡體   English   中英

Angular 如何將 *ngFor 與異步 pipe 一起使用?

[英]Angular how do I use *ngFor with the Async pipe?

嗨,我在使用異步 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 頁面不做插孔

確保您的消息 object 是Observable 類型 並添加一個 null 檢查,然后用ngIf循環它,一旦你消息 observable 有一些數據,下面的代碼就可以正常工作

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

感謝那些仍在回答這個問題的人,但我從第一條評論中解決了這個問題,問題是:我很愚蠢,我將服務器中的數據分配給方法本地的數組而不是組件的屬性,如果我這樣做會從一開始就起作用嗎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM