Angular/rxjs/Subject/BehaviorSubject share http service data across multiple components

徘徊边缘 提交于 2019-12-06 05:20:19

Several points to make it work :

  1. To make sure the data is loaded before the routes are reached, you can use a resolver. The resolver will be linked to your route paths, and will be a function that will execute the Http request before the route is resolved.
  2. You need to store your data in a store once the call has been made. That can be done with external stores such as @Ngrx, but the most basic example is to use a variable inside your service (even better with getter / setter) :

example service :

_equipmentDetails: any  // Should be private in use-case

...

getEquipmentDetail(clientId, modemId): Observable<any> {
  const url = 'myOwnUrl';

  return this.Http
    .get(url)
    .map(result => {
      if (result) {
        // Notice how I set the value from the Http call.
        return this._equipmentDetails = result.json();
      }
    })
    .catch(this.handleError);
}

And then you can get the property value from your components through dependency injection.

  constructor(
    ...
    private equipmentService: ServiceClass,
  ) {
    this.equipmentService._equipmentDetails;
  }

Solved this by using a shared service. I was doing this before BUT in my shared service I was using a Subject instead of a BehaviorSubject. The Subject does not cache data so I thought my design pattern was not working. When changed to a BehaviorSubject everything worked perfectly.

CustomerPortalBaseComponent makes all the HTTP calls for data that will be shared across this app module. It then sends the message to shared service and the other components (main components for route) subscribe to that service. EX:

CustomerPortalBaseComponent

this.applicationsMessagingService.sendMessage(data)

ApplicationsMessagingService:

Injectable()
export class ApplicationsMessagingService {

  private subject = new BehaviorSubject<any>(null);

  sendMessage(message: {}) {
   this.subject.next(message);
  }

  clearMessage() {
   this.subject.next(null);
 }

  getMessage(): Observable<any> {
   return this.subject.asObservable();
  }

}

CustomerPortalDashboardComponent

ngOnInit() {
this.subscription = this.applicationsMessagingService.getMessage().subscribe(message => {
  this.message = message;
  this.handleApplicationData(this.message);
});


handleApplicationData(data: any){
  if (data){
   this.applicationData = data;
 }
}

applicationData is then passed to child components and received via @input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!