在我的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;
- })
- }
- }
这是我编译时得到的Type错误
- 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转换成任何一个来解决这个问题,但这不会破坏使用Typescript的意义吗?
对我出错的地方有任何帮助都会很棒
提前致谢
解决方法
有两种方法可以做到这一点,它取决于您使用的RxJS / Angular版本.以下是根据您的版本执行此操作的两种方法:
- // Using RxJS v4 / Angular v2-4. I assume that you're using the HttpModule...
- import 'rxjs/add/operator/map';
- public getUsers(url: string): Observable<IUser[]> {
- return this._http.get(url)
- .map((response: Response) => <IUser[]>response.json());
- }
- // Using RxJS v5 / Angular 5+ (at the moment). I assume that you're using the HttpClientModule,as the HttpModule was deprecated in Angular v4.
- public getUsers(url: string): Observable<IUser[]> {
- return this._http.get<IUser[]>(url);
- }