Notify component when service function is complete

2019-09-05 07:51发布

问题:

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.

回答1:

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



回答2:

There is another way to call data each and every component with Rxjs framework, Make sure services should be reusable for all component, so do much as u can do code in services and subscribe only in component :

Services

 import { Injectable } from 'angular2/core';    
 import { Http } from 'angular2/http';
 import { Result} from './models/result'; // model imported
 import { BehaviorSubject } from 'rxjs/BehaviorSubject';

 @Injectable()
 export class Service {
   private _result: Result[];

   constructor(private http: Http) {
     this.result$ = new BehaviorSubject<Result[]>(this._result)
   }
   result$: BehaviorSubject<Result[]>;
   private _urlGet = '/api';

   getPlacesForUser(): void{
     this.http.get(this._urlGet)
      .map(res => JSON.parse(res.text()))
      .catch(error => console.log(error))
      .subscribe(result => {
         this.result = result;
       })
    }
 }

Component

 constructor(private _service: Service)
 ngOnInit(): any {
   this._service.result$.map(result => result.filter(res => 
    res.id)).subscribe(
        result => this.result = result); // map is optional to filter json
  }