gpt4 book ai didi

javascript - 类型 'Observable' 不可分配给类型 'Observable'
转载 作者:可可西里 更新时间:2023-11-01 01:20:43 26 4
gpt4 key购买 nike

在我的 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 的意义吗?

任何关于我哪里出错的帮助都是很好的

提前致谢

最佳答案

有两种方法可以做到这一点,这取决于您使用的是哪个版本的 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);
}

关于javascript - 类型 'Observable<Object>' 不可分配给类型 'Observable<IUser[]>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837692/

26 4 0