Angular 4.3 HttpClient响应对象

时间:2017-08-09 15:48:59

标签: angular

我一直在将我的服务从Angular 4.3切换到新的HttpClient。

return this._http.get<ValidateEmailResponse>(`${_validateEmailApi}`, { params })
    .catch(this.handleError);

但是,响应的类型为<Object>,而不是<ValidateEmailResponse>

,例如;

enter image description here

是否应该宣布?

1 个答案:

答案 0 :(得分:2)

这就是我的代码现在使用新的4.3 HttpClient(见下文)。注意我的方法的返回类型。

getProducts(): Observable<IProduct[]> {
    return this._http.get<IProduct[]>(this._productUrl)
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

private handleError(err: HttpErrorResponse) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage = '';
    if (err.error instanceof Error) {
        // A client-side or network error occurred. Handle it accordingly.
        errorMessage = `An error occurred: ${err.error.message}`;
    } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }
    console.error(errorMessage);
    return Observable.throw(errorMessage);
}