简体   繁体   中英

returning observable from Angular5 http.get

I have an Interface

export interface IEmployee{
  id: string;
  first_name: string;
}

In my employee.service.ts

  getEmployess():Observable<IEmployee>{
    return this._http.get<IEmployee>(this._dataUrl);
  }

In my component

  employees:Array<IEmployee>;   

  constructor(private _employeeService:EmployeeService){
    this._employeeService.getEmployess()
      .subscribe(
        (data) => {
          this.employees = data;
          console.log(data);
        }
      )
  }

I am gettign the erro [ts] Type 'IEmployee' is not assignable to type 'IEmployee[][]'.

I am unable to understand whats wrong. I want that the returned data from service should be stored in employees array.

Please help.

return

 getEmployess():Observable< Array<IEmployee>>{
    return this._http.get<Array<IEmployee>>(this._dataUrl);
  }

or

getEmployess():Observable< IEmployee[]>{
    return this._http.get<IEmployee[]>(this._dataUrl);
  }

Reason of issue:

this.employees = data;  
// this.employees is type of IEmployee[]
// data is type of IEmployee

Solution -> Just change :

getEmployess():Observable<IEmployee>

To

getEmployess():Observable<IEmployee[]>{
// OR
getEmployess():Observable<Array<IEmployee>>{

As you are getting array of IEmployee in return and you have defined employees:Array<IEmployee>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM