Search code examples
design-patternsangularangular2-services

Notify component when service function is complete in angular


I writing a service which do a http query to the backend:

getPlacesForUser(){
 this.http.get("http://localhost:8080/processPlaces")
  .map(res => res.text())
  .subscribe(
    data => this.result = data,
    err => this.logError(err),
    () => console.log('Places Request completed')
  )
}

Now I want to update the components-side, if the request is completed:

processPlaces(){
 this._backendService.getPlacesForUser();
}

How can I communicate between the component and service?

Furthermore I searching for the best practice.


Solution

  • In fact, you can return the observble directly from the getPlacesForUser method and attach a subscribe method on it.

    • Service

      getPlacesForUser(){
        return this.http.get("http://localhost:8080/processPlaces")
          .map(res => res.text());
      }
      
    • Component

      processPlaces(){
       this._backendService.getPlacesForUser()
        .subscribe(
          data => this.result = data,
          err => this.logError(err),
          () => console.log('Places Request completed')
        );
      }
      

    The result attribute corresponds to an attribute of the component you can use in the component.

    You can notice that a async pipe is available to directly leverage observable in expressions (for example within an ngFor one).

    I think that this answer could help you: How to Consume Http Component efficiently in a service in angular 2 beta?.

    Hope it helps you, Thierry