I am new to angularJs2. I have created following service:
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);
}
}
Following are my Typescript compile configuration of Vs2017
When I compile the code using visual studio 2017 I get following error
**TS2322 Build:Type 'Promise<void>' is not assignable to type 'Promise<customType[]>'.*
*
Help me to fix this error.
The "Type 'Promise' is not assignable to type" TypeScript error occurs when we try to assign a value that has a type of Promise to a value that has an incompatible type. To solve the error, resolve the Promise and make the two values of compatible types before the assignment.
The error "Argument of type 'void' is not assignable to parameter of type" occurs when we forget to return from a function and pass a void argument to the calling function. To solve the error, make sure you return a value of the expected type, before passing it to the caller.
When a function definition has a void return type, it means the function must not return anything. If you need to resolve the Promise with a value of another type, pass the specific type to the generic. Copied! The Promise above can only be resolved with a number.
You are not returning anything inside your then
which makes jobs
be of type Promise<void>
. Return the array inside 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;
}
See the chaining behaviour of promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With