0

Any help in this concept will be deeply appreciated. I am looking to store the list of employees from the first call of API in Angular as observable. But for all the consecutive calls I want to use the stored listOfEmployees . I tried various approaches with no luck.

My Employee.ts class

export class Employee 
{
    EmployeeName: string;
    Department: string; 
}

My Service.ts class

getListOfEmployeeFromAPI(data: any): Observable<Employee[]> {

  if(!!this.listOfEmployees) //Check if Employee list if stored earlier by the first call. If the list is empty then call API else get the Employee list from the variable listOfEmployees
  {

  let _url = this.myLocalURL+'GetEmployeeList';
  return this.http.post<Employee[]>(_url,data).
  pipe(
    tap(result =>
      {
       this.storeEmployeeRecords(result);
      }
      ),   
    catchError(err=>{return this.errorHandler(err)})     
    );    
   
   }
   else 
   {
      //How to return observable here.
   }

}


listOfEmployees:Employee[];

//Here I am storing the list of employess in the local variable.
storeEmployeeRecords(ListOfEmployees:Employee[])
{
    this.listOfEmployees = ListOfEmployees;
}
Suzane
  • 193
  • 1
  • 3
  • 13
  • 1
    Does this answer your question? [How to create an Observable from static data similar to http one in Angular?](https://stackoverflow.com/questions/35219713/how-to-create-an-observable-from-static-data-similar-to-http-one-in-angular) – A_A Sep 28 '21 at 09:55
  • You can return like `return Of(this.listOfEmployees)`. You can optimise your code using `take(1)` and `share()` or `shareReply()` – navnath Sep 28 '21 at 09:57
  • Awesome! thanks this is what I was looking for perhaps private listofEmployees:BehaviorSubject = new BehaviorSubject([]); storeEmployeeRecords(ListOfEmployees:Employee[]) { this.listOfEmployees.next(ListOfEmployees); } – Suzane Sep 28 '21 at 10:17

0 Answers0