【发布时间】:2017-12-15 22:48:36
【问题描述】:
使用角度 5.1。
返回任何对象的Observable 都有效
getGlassPartsForVin(vin: string): Observable<GlassPartsResponse> {
return this.httpClient.get<GlassPartsResponse>(
`/api/vin/${vin}`,
this.getRequestOptions()
);
}
返回 boolean 或 int 不会:
getHasAccess(): Observable<boolean> {
return this.httpClient.get<boolean>(
"api/permission/hasaccess",
this.getRequestOptions());
}
投掷:
error TS2322: Type 'Observable<HttpEvent<boolean>>' is not assignable to type 'Observable<boolean>'.
Type 'HttpEvent<boolean>' is not assignable to type 'boolean'.
如果我从 api 返回的只是true 或false,我该怎么办?
编辑: 复制 https://stackblitz.com/edit/angular-mzgfdg
vscode 提供更多信息,似乎是 booleannot beingobject 的问题`
Type 'Observable<HttpEvent<Boolean>>' is not assignable to type 'boolean | Observable<Boolean>'.
Type 'Observable<HttpEvent<Boolean>>' is not assignable to type 'Observable<Boolean>'.
Type 'HttpEvent<Boolean>' is not assignable to type 'Boolean'.
Type 'HttpSentEvent' is not assignable to type 'Boolean'.
Types of property 'valueOf' are incompatible.
Type '() => Object' is not assignable to type '() => boolean'.
Type 'Object' is not assignable to type 'boolean'.
EDIT2:我通过在 getRequestOptions() 方法中返回 { headers: HttpHeaders } 而不是 any 来修复它。有了这个我已经开始使用这个方法签名:
get<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
而不是我使用any:
get<T>(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'events';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<T>>;
我仍然对这如何产生影响感到有些困惑
【问题讨论】:
-
this.getRequestOptions()似乎是发布的代码中的问题。因为它没有定义。 -
本来和@davidxxx 一样。您的问题在于请求选项!
-
这是真的,但是显示的另一个错误是相同的。奇怪的是,如果我删除该行,错误就会消失。我认为这可能是由于
options的类型为any -
我已更新链接以避免混淆
标签: angular typescript