繁体   English   中英

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

[英]returning observable from Angular5 http.get

我有一个界面

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

在我的employee.service.ts中

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

在我的组件中

  employees:Array<IEmployee>;   

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

我很错误[ts]类型'IEmployee'不能分配给类型'IEmployee [] []'。

我不明白怎么了。 我希望服务返回的数据应存储在employee数组中。

请帮忙。

返回

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

要么

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

问题原因:

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

解决方案 ->只需更改:

getEmployess():Observable<IEmployee>

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

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

暂无
暂无

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

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