首页 > 解决方案 > 以角度存储可观察的数据列表以进行第一次调用并使用存储的值

问题描述

对此概念的任何帮助将不胜感激。我希望将 Angular 中第一次调用 API 的员工列表存储为可观察的。但是对于所有连续的呼叫,我想使用存储的 listOfEmployees 。我尝试了各种方法,但没有运气。

我的 Employee.ts 类

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

我的 Service.ts 类

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;
}

标签: angulartypescriptobservable

解决方案


推荐阅读