从Angular5 http.get返回observable
我有一个接口从Angular5 http.get返回observable,angular,Angular,我有一个接口 export interface IEmployee{ id: string; first_name: string; } 在我的employee.service.ts中 getEmployess():Observable<IEmployee>{ return this._http.get<IEmployee>(this._dataUrl); } getEmployess():可观察{ 返回此。_http.get(此。_数据URL
export interface IEmployee{
id: string;
first_name: string;
}
在我的employee.service.ts中
getEmployess():Observable<IEmployee>{
return this._http.get<IEmployee>(this._dataUrl);
}
getEmployess():可观察{
返回此。_http.get(此。_数据URL);
}
在我的组件中
employees:Array<IEmployee>;
constructor(private _employeeService:EmployeeService){
this._employeeService.getEmployess()
.subscribe(
(data) => {
this.employees = data;
console.log(data);
}
)
}
员工:数组;
建造商(私人雇员服务:雇员服务){
这是._employeeService.getEmployeess()
.订阅(
(数据)=>{
这是指员工=数据;
控制台日志(数据);
}
)
}
我正在将erro[ts]类型“IEEMPLOYEE”不可分配给类型“IEEMPLOYEE[][]”。
我不明白出了什么问题。我希望服务返回的数据应该存储在employees数组中
请帮助。问题原因:
this.employees = data;
// this.employees is type of IEmployee[]
// data is type of IEmployee
解决方案->只需更改:
getEmployess():Observable<IEmployee>
getEmployess():可观察
到
getEmployess():可观察{
//或
getEmployess():可观察{
作为回报,您将获得IEEMPLOYEE
数组,并且您已经定义了
employees:Array;
发行原因:
this.employees = data;
// this.employees is type of IEmployee[]
// data is type of IEmployee
解决方案->只需更改:
getEmployess():Observable<IEmployee>
getEmployess():可观察
到
getEmployess():可观察{
//或
getEmployess():可观察{
作为回报,您将获得IEEMPLOYEE
数组,并且您已经定义了
employees:Array;
返回
getEmployess():Observable< Array<IEmployee>>{
return this._http.get<Array<IEmployee>>(this._dataUrl);
}
getEmployess():可观察{
返回此。_http.get(此。_数据URL);
}
或
getEmployess():可观察{
返回此。_http.get(此。_数据URL);
}
返回
getEmployess():Observable< Array<IEmployee>>{
return this._http.get<Array<IEmployee>>(this._dataUrl);
}
getEmployess():可观察{
返回此。_http.get(此。_数据URL);
}
或
getEmployess():可观察{
返回此。_http.get(此。_数据URL);
}
您的服务返回类型是可观察的。因此,此可观察对象发出的每个事件都是一个IEEmployee。您试图将该IEEmployee存储到数组类型的变量中。这不起作用。鸡蛋盒与鸡蛋不同。您的服务返回类型是可观察的。因此,此可观察对象发出的每个事件都是一个IEEmployee。您正在尝试吗将该雇员存储到数组类型的变量中。这不起作用。蛋盒与蛋不是一回事。通过指定一个变量取消订阅更好通过指定一个变量取消订阅更好