繁体   English   中英

类型“void”不可分配给对象

[英]Type 'void' is not assignable to object

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

得到了用于从 API 控制器检索数据的代码。 在 ts 中编译它时,我总是收到此错误:

Type 'Promise<void | LoginInfo>' is not assignable to type 'Promise<LoginInfo>'
Type 'void' is not assignable to type 'LoginInfo'

这是我的软件包版本:

"typescript": "2.5.2",
"@angular/compiler": "4.3.6"
"@angular/compiler-cli": "4.3.6"

您需要在错误处理案例中返回一些内容或抛出一个新错误。 该方法承诺返回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) {
        this.handleError(error);
        return null;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM