我正在尝试使用 angular 2 HttpClient 通过 REST 获取数据。我在这里关注 Angular 教程 https://angular.io/tutorial/toh-pt6在 Heroes 和 HTTP 部分下,您会看到这段代码用于通过 http 获取英雄数据。
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
下面是我在申请中写的类似版本
fetch(startIndex: number, limit: number): Promise<Order[]> {
let url = this.baseUrl + "&startIndex=" + startIndex + "&limit=" + limit;
return this.http.get(url)
.toPromise()
.then(response => response.json().results as Order[])
.catch(this.handleError);
}
我正在使用 InteliJ Idea,调用 response.json() 时有一条红线,甚至当我尝试使用 ng build 进行构建时,我也会收到错误。
Property 'json' does not exist on type 'Object'.
您可能会注意到,我有 json().results
而不是 json().data
。那是因为根据教程,服务器响应一个具有 data
字段的对象,但我自己的服务器响应一个具有 results
字段的对象。如果向下滚动教程,您会看到这一点。
Note the shape of the data that the server returns. This particular in-memory web API example returns an object with a data property. Your API might return something else. Adjust the code to match your web API.
为了解决这个问题,我尝试了这样的方法
(response: Response) => response.json().results as Order[]
当我这样做时,.json() 方法已得到解决,但弹出另一个错误
Property results does not exist on type Promise
我试着通过定义一个接口(interface)来解决这个问题
interface OrderResponse {
orders: Order[];
}
并将get调用修改为
.get<OrderResponse>(url)...
但这也没有用。弹出另一个错误
Type 'OrderResponse' is not assignable to type 'Response'.
需要注意的是,在教程中他们使用了 Angular HttpModule,但在我的应用程序中我使用的是新的 Angular HttpClientModule,所以可能这就是错误的来源。
我是 Angular 2 的新手,这是我用它构建的第一个应用程序。如果以上代码对新的 HttpClientModule 不再有效,我将不胜感激任何有关如何使用新的 HttpClientModule 实现相同目的的帮助。
我发现了类似的问题Property 'json' does not exist on type '{}'和 Property does not exist on type 'object'但是那里的答案都没有帮助我。
更新
正如评论所建议的那样,新的 HttpClientModule 中没有 .json() 方法。对于如何使用新模块实现同样的效果,我仍然很感激。根据指南,他们做了这样的事情
http.get<ItemsResponse>('/api/items').subscribe(data => {
// data is now an instance of type ItemsResponse, so you can do this:
this.results = data.results;
});
我完全理解,但我的问题是,该代码不在组件内,而是在服务内,因此调用订阅并将结果分配给实例字段没有多大意义。
我需要我的服务返回包含在 Promise 中的一组订单。我的组件可以像这样调用
this.orderService.fetch(0, 10).then(orders => this.orders = orders)
我还想在我的服务获取方法中声明一个局部变量,这样我就可以做
.subscribe(data => {
this.orders = data.results;
}
// and out of the get call I return my local variable orders like
return Promise.resolve(orders)
但这对我来说没有多大意义,因为对 .get() 的调用是异步的,并且该方法甚至可能在获取所有数据之前就返回,并且订单数组可能为空。
更新
这里要求的是handleError的代码
private handleError(error: any): Promise<any> {
console.log('An error occured ', error);
return Promise.reject(error.message || error);
}
最佳答案
对于 future 的访问者:在新的 HttpClient
中(Angular 4.3+),response
对象默认是 JSON,所以你不需要再做 response.json().data
了。直接使用response
即可。
示例(根据官方文档修改):
import { HttpClient } from '@angular/common/http';
@Component(...)
export class YourComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://api.github.com/users')
.subscribe(response => console.log(response));
}
}
不要忘记导入它并在项目的 app.module.ts 中包含 imports 下的模块:
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module after BrowserModule.
HttpClientModule,
...
],
...
关于angular - 类型 'json' 上不存在属性 'Object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46005430/