类型Promise <void>不能分配给Promise <customtype []>类型

时间:2017-05-09 03:53:00

标签: javascript angular typescript visual-studio-2017

我是angularJs2的新手。我创建了以下服务:

fts(3)

以下是Vs2017的Typescript编译配置

enter image description here

当我使用visual studio 2017编译代码时,我收到以下错误

import { Injectable, OnInit } from '@angular/core'; import { customType } from '../models/currentJobs'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class JobService implements OnInit { constructor(private http: Http) { } ngOnInit(): void { this.getCurrentJobs(); } private headers: Headers = new Headers({ 'Content-Type': 'application/json' }); private ordersUrl: string = 'http://localhost:35032/api/order/'; public orders: customType[]; getCurrentJobs(): Promise<customType[]> { var jobs = this.http.get(this.ordersUrl) .toPromise() .then(response => { this.orders = response.json() as customType[]; }) .catch(this.handleError); return jobs;//this line throws error } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } } *

帮我修复此错误。

2 个答案:

答案 0 :(得分:6)

您未在then内返回任何内容,因为jobs属于Promise<void>类型。返回then内的数组:

getCurrentJobs(): Promise<customType[]> {
    var jobs = this.http.get(this.ordersUrl)
      .toPromise()
      .then(response => {
        this.orders = response.json() as customType[];
        return this.orders;
      })
      .catch(this.handleError);
    return jobs;
}

查看承诺的链接行为:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining

答案 1 :(得分:-1)

我已经添加了&#39; catch&#39;运算符,并将您的接口导入交换为代码中的接口定义(因为我显然无法访问您的接口)。在没有其他项目代码的情况下,我无法对此进行测试,但它看起来对我来说并不会在VSC中抛出任何错误。

import { Injectable, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';


export interface customType{
}


@Injectable()
export class JobService implements OnInit {

    constructor(private http: Http) { }
    private jobs: Promise<customType[]>;

    ngOnInit(): void {
        this.jobs = this.getCurrentJobs();
    }

    private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
    private ordersUrl: string = 'http://localhost:35032/api/order/';

    public orders: customType[];

    getCurrentJobs(): Promise<customType[]> {
        return this.http.get(this.ordersUrl)
          .map(response => response.json())
          .catch(this.handleError)
          .toPromise();

    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}