angular - 角,键入“承诺”'
问题描述
编译项目时出现此错误。错误终端:
ERROR in src/app/services/task.ts(44,5): error TS2322: Type
'Promise<void | Task>' is not assignable to type 'Promise<Task>'.
Type 'void | Task' is not assignable to type 'Task'.
Type 'void' is not assignable to type 'Task'.
这是消除错误的代码。
26 loadTasks(): Promise<Task[]> {
27 const url = `${this.tasksUrl}?access_token=${localStorage.getItem('token')}`;
28 return this.http.get(url)
29 .toPromise()
30 .then(res => res.json() as Task[])
31 .catch(error => this.handleError(error, 'Could not load tasks!'));
32 }
33 getTask(id: number): Promise<Task> {
34 const url = `${this.tasksUrl}/${id}?access_token=${localStorage.getItem('token')}`;
35 return this.http.get(url)
36 .toPromise()
37 .then(res => res.json() as Task)
38 .catch(error => this.handleError(error, 'Could not load task!'));
39 }
40 create(task): Promise<Task> {
41 task['due_date'] = task['due_date']['formatted'];
42 let body = JSON.stringify({task: task});
43 const url = `${this.tasksUrl}?access_token=${localStorage.getItem('token')}`;
44 return this.http.post(url, body, { headers: this.headers })
45 .toPromise()
46 .then(res => res.json() as Task)
47 .catch(error => {
48 this.handleError(error, 'Could not create task!')
49 });
50 }
51
52 update(task) {
53 const url = `${this.tasksUrl}/${task.id}?access_token=${localStorage.getItem('token')}`;
54 if (task['due_date'] && task['due_date']['formatted']) {
55 task['due_date'] = task['due_date']['formatted'];
56 }
57 return this.http.put(url, JSON.stringify(task), { headers: this.headers })
58 .toPromise()
59 .then(res => res.json() as Task)
60 .catch(error => {
61 this.handleError(error, 'Could not update task!')
62 });
63 }
这是我对代码进行更改时终端中的错误。
create(task): Promise<Task | void>
error terminal:
ERROR in src/app/components/tasks/form.ts(62,26): error TS2345: Argument of type 'void | Task' is not assignable to parameter of type 'Task'.
Type 'void' is not assignable to type 'Task'.
告诉我如何解决这个错误,我将不胜感激。
解决方案
最近我将打字稿更新为版本后遇到了同样的问题2.7.2
我通过更改catch
阻止来修复它。我的errorHandler()
抛出异常Observable.throw
类型ErrorObservable
我只是Observable.throw
从我正在调用的自定义方法中链接了errorHandler()
. 在你的情况下create()
你可以这样做
create(task): Promise<Task> {
task['due_date'] = task['due_date']['formatted'];
let body = JSON.stringify({task: task});
const url = `${this.tasksUrl}?access_token=${localStorage.getItem('token')}`;
return this.http.post(url, body, { headers: this.headers })
.toPromise()
.then(res => res.json() as Task)
.catch(error => {
Observable.throw(this.handleError(error, 'Could not create task!')); // chain Observable.throw
});
}
推荐阅读
- c# - 如何查询特定类型然后获取基础文档
- javascript - 创建新数组产生未定义的函数
- c# - 为什么关闭连接后可打印项目从打印队列中消失并且没有任何反应?
- testing - 播放:自动化测试数据设置
- javascript - 在 React Final Form 中,为嵌套字段提供初始值
- reflection - 声明后如何访问 ProtoField 的名称?
- linux - Linux Xdebug(再次)
- jupyter-notebook - 事件循环在启动 jupyter notebook 时运行错误
- python - 随机化 DataFrame 行
- python - 如何在 keras 中建模共享层?