angular - 如何正确处理这个 Angular 承诺以返回一个对象数组?
问题描述
我是 Angular 的新手,我发现了以下问题。
进入服务类我有这个:
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http'
@Injectable()
export class EventService {
constructor(private http: HttpClient) {}
getEvents() {
return this.http.get('assets/json_mock/calendarevents.json')
.toPromise()
.then(res => JSON.parse(JSON.stringify(res)).data)
.then(res => console.log(res))
.then(res => { return res })
}
}
因此getEvents()方法通过get()方法对我的服务器上的 URL 执行调用,并通过 **toPromise() 方法将此可观察对象转换为 Promise。
然后我将响应的结果转换为 JSON 对象,并将这个 JSON 的数据字段放入res中。
将它打印到控制台中,这是我所期望的,这是输出:
(3) [{…}, {…}, {…}]
0: {id: 1, title: "All Day Event", start: "2017-02-01"}
1: {id: 2, title: "Long Event", start: "2017-02-07", end: "2017-02-10"}
2: {id: 3, title: "Repeating Event", start: "2017-02-09T16:00:00"}
length: 3
__proto__: Array(0)
最后我通过这一行返回它:
.then(res => { return res })
好的,在我的 Angular 组件中,我必须使用这些数据,在这里我发现了一些问题。我试图通过这一行来做到这一点:
this.eventService.getEvents().then(events => { this.events = events;});
但是 IDE 给了我以下错误信息:
类型 'void' 不可分配给类型 'any[]'.ts(2322)
试图编译我得到一个类似的错误:
ERROR in src/app/fullcalendar/fullcalendar.component.ts:22:52 - error TS2322: Type 'void' is not assignable to type 'any[]'.
22 this.eventService.getEvents().then(events => { this.events = events;});
~~~~~~~~~~~
为什么我会收到此错误?究竟是什么意思?我该如何尝试修复它?
我认为我的服务方法正在返回一个包含 JSON 的承诺,但这也可能是错误的,因为我的组件类需要一个包含 JSON 对象的对象数组。数组以这种方式在组件代码中声明(我无法更改它,因为它被 PrimeNG 日历使用):
events: any[];
我该如何解决这个问题?
解决方案
当您登录到控制台时,您没有返回值。所以从那里的价值是void
。
然后,您将此 void 值分配给this.events
. 显然这应该是一个由任何 ( any[]
) 组成的数组。所以这就是信息告诉你的错误。
// should assign a typescript return type to the method to detect the error earlier
getEvents(): Promise<any[]> {
return this.http.get('assets/json_mock/calendarevents.json')
.toPromise()
.then(res => JSON.parse(JSON.stringify(res)).data)
.then(res => {
console.log(res);
// you returned no value here!
return res;
})
}
推荐阅读
- c++ - 使用 boost::future .then() 将延续任务添加到同一个线程池
- reactjs - Firebase 托管上的 Nextjs 在页面刷新时返回 404
- content-type - 如何阅读 Vapor 4 上的 apple-app-site-association 文件?
- ssl - 如果启用了 SSL,则 Tomcat 9.0.31 中的异常(仅通过减少 MTU 的 VPN 发生)
- javascript - Window.location.href 在 onmessage 事件中不起作用?
- python - Sending json requests to flask server in pytest
- android - React Native:当应用程序置于后台时,MainActivity 被销毁,当它上面有第二个活动时
- npm - Cube.js 问题错误:npm install --save-dev @cubejs-backend/cubestore-driver 失败,退出代码为 1
- react-native - takeEvery$1 需要一个模式或通道反应原生
- vue.js - 使用向上/向下按钮更改对象数组的顺序