简体   繁体   中英

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

Hi I'm having problems with using the asynchronous ngFor, I've got the simplest example of this thing, an array of objects that is obtained from a server onInit, and I want to iterate on int once it arrives,this is how I've written it on the template:

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

I mean it looks ok to me but apparently not, here's the ts part:

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);
    })
  }

the section regarding the question is the loadChat method which is called in a method called in the onInit, so basically it is called in the on init, and the declaration of the array

point is the array gets defined I even print it on the console but the html page doesn't do jack

Make sure your message object is of type Observable . and Add a null check before looping over it with a ngIf once you messages observable has some data this below code will work fine

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

Thanks to those who are still answering this but I solved it from the first comment and the problem was: I'm stupid and I assigned the data from the server to an array local to the method instead of the property of the component, if I did that it would have worked from the begininng

lmao

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM