Reputation: 734
export class LoginInfo {
userName: string;
password: string;
}
public getLoginInfo(id: number): Promise<LoginInfo> {
return this.http.get(this.url + id + '/' + '/loginInfo')
.toPromise()
.then(response => response.json() as LoginInfo)
.catch((error: Response) => {
this.handleError(error);
});
}
Got this code for retrieving data from API controller. When compiling it in ts, I am always getting this error:
Type 'Promise<void | LoginInfo>' is not assignable to type 'Promise<LoginInfo>'
Type 'void' is not assignable to type 'LoginInfo'
Here are my package versions:
"typescript": "2.5.2",
"@angular/compiler": "4.3.6"
"@angular/compiler-cli": "4.3.6"
Upvotes: 2
Views: 2321
Reputation: 249546
You need to return something on the error handling case or throw a new error. The method promises to return a LoginInfo
but if an error occurs you return nothing, typescript protect you from accidentally returning nothing, if that is what you want you should return null explicitly:
public getLoginInfo(id: number): Promise<LoginInfo> {
return this.http.get(this.url + id + '/' + '/loginInfo')
.toPromise()
.then(response => response.json() as LoginInfo)
.catch((error: Response) => {
this.handleError(error);
// return null;
throw new Error();
});
}
As a side note, the async/await version may be more readable:
public async getLoginInfo(id: number): Promise<LoginInfo> {
try{
let response = await this.http.get(this.url + id + '/' + '/loginInfo').toPromise();
return response.json() as LoginInfo;
} catch (error) {
this.handleError(error);
return null;
}
}
Upvotes: 9