Home > OS >  How do I know that this function has completed and returned something? angular
How do I know that this function has completed and returned something? angular

Time:03-09

I call this function in the component

this.contactsService.loadChat(chatListItem);

How do I know that this function has completed and returned something? here are the insides

 loadChat(chatListItem: ListItem) {
    this.whatsappApiService
      .getMessages(chatListItem.contactId, 1, 25)
      .subscribe((loadedMessages: Message[]) => {
        this.whatsappContactsFacade.loadedChats(loadedMessages);
        this.loadedSubject.next(true);
      });
  }

CodePudding user response:

You could pass a callback function when the function is done the callback will get called, the code for this will look something like this

this.contactsService.loadChat(chatListItem, () => {alert("i'm a callback function")});

 loadChat(chatListItem: ListItem, callback) {
    this.whatsappApiService
      .getMessages(chatListItem.contactId, 1, 25)
      .subscribe((loadedMessages: Message[]) => {
        this.whatsappContactsFacade.loadedChats(loadedMessages);
        this.loadedSubject.next(true);
        callback() // callback gets called here
      });
  }

CodePudding user response:

Just like Sarkar said just before, you can use callbacks.

You can either use the simple way as he said but you can also modulate the message sent depending of if it's an error or the appropriate behavior.

For example, if whatsappApiService.getMessages() can't return an observable, it will trigger an error that will be displayed in a dedicated alert.

this.contactsService.loadChat(chatListItem, (msg) => {alert(msg)});

loadChat(chatListItem: ListItem, callback) {
    this.whatsappApiService
      .getMessages(chatListItem.contactId, 1, 25)
      .subscribe((loadedMessages: Message[]) => {
        this.whatsappContactsFacade.loadedChats(loadedMessages);
        this.loadedSubject.next(true);
        callback() // callback gets called here
      })
    .then(() => {
        //Behavior if everything is fine
        this.msg = "It's all good";
    })
    .error((err) => {
        //Behavior if there is a problem
        this.msg = "Error : "   err;
    });
}
  • Related