raju
raju

Reputation: 6946

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.

Upvotes: 0

Views: 56

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58593

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

Upvotes: 1

rijin
rijin

Reputation: 1757

return

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

or

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

Upvotes: 2

Related Questions