简体   繁体   English

从Angular5 http.get返回可观察到的

[英]returning observable from Angular5 http.get

I have an Interface 我有一个界面

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

In my employee.service.ts 在我的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[][]'. 我很错误[ts]类型'IEmployee'不能分配给类型'IEmployee [] []'。

I am unable to understand whats wrong. 我不明白怎么了。 I want that the returned data from service should be stored in employees array. 我希望服务返回的数据应存储在employee数组中。

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>; 当您获取IEmployee数组作为回报时,您已经定义了employees:Array<IEmployee>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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