2017-05-09 114 views
0

我是angularJs2的新手。我創建了以下服務:類型Promise <void>不可分配類型Promise <customType []>

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); 
    } 
} 

以下是我的打字稿編譯Vs2017

enter image description here

的配置當我使用的Visual Studio 2017年我獲得以下錯誤

**TS2322 Build:Type 'Promise<void>' is not assignable to type 'Promise<customType[]>'.* *

編譯代碼

幫我解決這個錯誤。

+0

如若'。那麼()'有'return'?沒有它,你覺得'工作'分配了什麼價值? – nnnnnn

+0

.then()返回一個Promise來完成執行過的回調函數。我在then() –

+0

的文檔中發現了這一點我很感謝你找到了你正在尋找的答案,但是我的更新答案仍然值得投票嗎?如果這是不正確的,那很好,但我不認爲它是這樣,並且反對票會阻止有人發現這個問題後來將其視爲他們問題的可能解決方案。謝謝! –

回答

-1

我已經添加了'catch'運算符,並將代碼中的接口定義的接口導入交換(因爲我顯然沒有訪問您的接口)。如果沒有剩下的項目代碼,我無法真正測試它,但它看起來很適合我,並且不會在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); 
    } 
} 
相關問題