" _this.http未定义"没原因

时间:2018-04-10 12:40:33

标签: angular typescript http ionic-framework

在我的LoginProvider中,我使用执行登录的函数并将创建的会话作为承诺返回。

@Injectable()
export class LoginProvider {

    constructor(public http: HttpClient) { };

    public async login(credentials: ICredentials): Promise<ISession> {

        let url: string = "https:/url/to/login";

        let headers: HttpHeaders = new HttpHeaders()

        let params: HttpParams = new HttpParams()
            .append("username", credentials.id)
            .append("password", credentials.password);

        return new Promise<ISession>((resolve, reject) => {
            this.http.get(url, { headers: headers, params: params }).subscribe((response: ILoginResponse) => {
                // handle response and return session
            }, (error: HttpErrorResponse) => {
                reject(error);
            })
        });
    }
}

问题在于,调用它时不知道this.http。调用此方法时出现以下错误。

"_this.http is undefined"

我不知道为什么在这个函数中应该定义http。我在构造函数中创建它,因此它应该可用于此函数,不应该吗?

1 个答案:

答案 0 :(得分:-1)

this内的new Promise指的是新的Promise对象,而不是LoginProvider个实例。

所以,而不是做

new Promise<ISession>((resolve, reject) => {
    this.http.get(...)
})

你应该简单

return this.http.get(url, { headers: headers, params: params}).toPromise()
  .then(response => // handle your response here then return your processed result);

(不要忘记导入'rxjs / add / operator / toPromise';)