参数类型的Typecscript和Angular错误



如何更正我在Angular中遇到的错误:

(response: HttpResponse<User>) => { 

给出的错误为:

Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(value: HttpResponse<User> | HttpErrorResponse) => void'.
Types of parameters 'response' and 'value' are incompatible.
Type 'HttpResponse<User> | HttpErrorResponse' is not assignable to type 'HttpResponse<User>'.
Type 'HttpErrorResponse' is missing the following properties from type 'HttpResponse<User>': body, clone

(response.body);给出错误

Argument of type 'User | null' is not assignable to parameter of type 'User'.
Type 'null' is not assignable to type 'User'.

我在Angular中使用的是typescript 4.5.5。

功能是:

public onLogin(user: User): void{
console.log(user)
this.subscriptions.push(
this.authenticationService.login(user).subscribe(
(response: HttpResponse<User>) => {
const token: string = response.headers.get(HeaderType.JWT_TOKEN) || '';
this.authenticationService.saveToken(token);
this.authenticationService.addUserToLocalCache(response.body);
this.router.navigateByUrl('/dashboard');
},
(error: HttpErrorResponse) => {
console.log(error);
this.sendErrorNotification(NotificationType.ERROR, error.error.message);
}
)
);
}

注意:我以前在另一个项目中使用过这个函数,该项目的typescript版本不同,没有这些问题。

问题1

我从AuthenticationService中的login方法中怀疑的是,您返回的Observable<HttpResponse<User> | HttpErrorResponse>与下面的代码类似:

login(user: User) {
return (
this.httpClient
.post<HttpResponse<User>>(/* Login API url */, user)
.pipe(catchError((err) => this.handleError(err)))
);
}
handleError(err: HttpErrorResponse) {
return of(err);
}

问题1的解决方案

而要Observable返回错误,以便另一个订阅能够获得它,您需要(rxjs(throwError:

import { throwError } from 'rxjs';
login(user: User) {
return (
this.httpClient
.post<HttpResponse<User>>(/* Login API url */, user)
.pipe(catchError((err) => this.handleAndThrowError(err)))
);
}
handleAndThrowError(err: HttpErrorResponse) {
return throwError(err);
}

问题2

来自HttpResponse<T>

class HttpResponse<T> extends HttpResponseBase {
constructor(init: { body?: T; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {})
body: T | null
...
}

response.body可能是null


问题2的解决方案

您可以使用对response.body执行空值检查

if (response.body)
this.authenticationService.addUserToLocalCache(response.body);

StackBlitz中的示例演示(具有多种场景(

最新更新