Search code examples
angulartypescriptangular-components

How to call the method from component to shared service


I have an angular application that I need to show the data based on the entered value

I am able to show the data in one component path is components/platform/annotation-my-task/annotation-pm-admin-list

In the above component I have created one method to call the API (by passing some payload) and fetched the data, and it is working fine.

annotation-pm-admin-list

getDetails(){
//here subscribed  the api and fetched the data
}

Now I need the same details in other component components/platform/annotation/annotation-process-list

So if I call the same API from the above component by creating the shared service it is not working.(because In API call we have passed some values which re accessed from other components)

So I am thinking to share the same method from annotation-pm-admin-list.ts to shared service and shard service to my other component, I don't know whether it is correct

What am I doing wrong? I am very new to angular and I would appreciate your help


Solution

  • The data you need sharing between the components should be in the service.

    In your case, I believe it is the data filter from annotation-pm-admin-list.

    1. Add a BehaviorSubject to your Service to store the filter (so the last value is retained);

    2. add methods/variables to your service to allow storing/accessing the filter and to perform the request from the stored filter:

      filter$ = new BehaviorSubject<Partial<YourFilterModel>>({})
    
      getData() {
          return this.filter$.pipe(
              take(1),
              switchMap(filter => this.http.post<YourDataModel>('your-url', filter))
          );
      }
    
    1. from the components, when you'd like to update the filter your call
     this.yourService.filter$.next({  attr1:'val-1', attr2: 'val2' })
    
    1. from the components, when you'd like to receive data (using the last used filter):
      data$ = this.yourService.getData()
    

    If you'd like to retail the last data received in your service, you could add a second BehaviorSubject to hold it:

      filter$ = new BehaviorSubject<Partial<YourFilterModel>>({})
      data$ = new BehaviorSubject<YourDataModel>({})
    
    
      constructor(....) { 
        this.filter$.pipe(
              switchMap(filter => this.http.post<YourDataModel>('your-url', filter)
        ).subscribe(data => this.data$.next(data))
      }
    

    in this second version, every time the filter$ variable is changed, a new request will be sent to your API. When it responds the latest data will be stored in the data$ subject

    1. from the components, when you'd like to update the filter your call
     this.yourService.filter$.next({  attr1:'val-1', attr2: 'val2' })
    
    1. from the components, when you'd like to receive the latest data stored in the service:
      data$ = this.yourService.data$