类型“()=>用户”上不存在属性“令牌”。任何

时间:2019-01-16 13:03:09

标签: angular

我收到一个错误

[ts]类型“()=>用户”上不存在属性“令牌”。 任何

我正在使用user.ts文件来
    export class User { id: number; username: string; password: string; firstName: string; lastName: string; token: string; }

这是我的身份验证服务ts文件:

export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public $currentUser: Observable<User>;

constructor(private http: HttpClient, ) {
    this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.$currentUser = this.currentUserSubject.asObservable();
   }
public currentUserValue(): User {
    return this.currentUserSubject.value;
}

实例化从身份验证服务ts到jwtinterceptor ts文件的函数时出现错误:

[ts]类型“()=>用户”上不存在属性“令牌”。 任何

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    let currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
        request = request.clone({
            setHeaders: { 
                Authorization: `Bearer ${currentUser.token}`
            }
        });
    }

    return next.handle(request);
}

2 个答案:

答案 0 :(得分:1)

您已将currentUserValue定义为一个函数,而不是属性,因此必须调用它来获取User数据。 您没有拨打this.authenticationService.currentUserValue

需要执行:

let currentUser = this.authenticationService.currentUserValue();

答案 1 :(得分:1)

使用此代码let currentUser = this.authenticationService.currentUserValue;,您将分配“功能”,而不是结果。

所以只需评估函数以获取返回的对象,替换为:

let currentUser = this.authenticationService.currentUserValue();