query
获取此代码用于从API控制器检索数据。在ts中编译时,我总是收到此错误:
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);
});
}
以下是我的软件包版本:
Type 'Promise<void | LoginInfo>' is not assignable to type 'Promise<LoginInfo>'
Type 'void' is not assignable to type 'LoginInfo'
答案 0 :(得分:3)
您需要在错误处理案例中返回一些内容或抛出新错误。该方法承诺返回LoginInfo
,但如果发生错误则不返回任何内容,打字稿保护您不会意外返回任何内容,如果这是您想要的,则应明确返回null:
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();
});
}
作为旁注,async / await版本可能更具可读性:
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: Response) {
this.handleError(error);
return null;
}
}