【发布时间】:2018-07-28 00:10:37
【问题描述】:
在我的 Api 服务中,我有一个简单的 getUsers 函数来获取 api 上的所有用户。
public getUsers(url: string): Observable<IUser[]> {
return this._http.get(url);
}
这是我的 IUser 界面,我现在已将所有字段设为可选。
export interface IUser {
id?: string;
first_name?: string;
last_name?: string;
location?: string;
followers?: string;
following?: string;
checkins?: string;
image?: string;
}
这是我在组件中使用该服务的方式:
export class SocialOverviewContainerComponent implements OnInit {
public userData = [];
public showForm = {};
private _apiService: ApiService;
constructor(apiService: ApiService) {
this._apiService = apiService
}
public ngOnInit(): void {
this.getUsersData();
}
public getUsersData() {
this._apiService.getUsers(ApiSettings.apiBasepath + 'users/')
.subscribe(users => {
this.userData = users;
})
}
}
这是我在编译时遇到的类型错误
ERROR in src/app/services/api.service.ts(18,5): error TS2322: Type 'Observable<Object>' is not assignable to type 'Observable<IUser[]>'.
Type 'Object' is not assignable to type 'IUser[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Property 'includes' is missing in type 'Object'.
我认为这可能是因为我的响应与界面不匹配,我对此进行了仔细检查,确实如此。而且我现在还将该字段设为可选以确保。
我知道我可以通过将 observable 强制转换为 any 来解决这个问题,但这不会破坏使用 Typescript 的意义吗?
任何关于我哪里出错的帮助都会很棒
提前致谢
【问题讨论】:
标签: javascript angular typescript interface observable