打字稿:无法为 Angular 项目中的接口 属性 设置值

Typescript: Unable to set value to interface property in Angular project

我正在 angular 并尝试使用以下代码使用 jwt 添加基本身份验证:

private authProvider(
    username: string,
    password: string
  ): Observable<IServerAuthResponse> {


    let accessToken: IServerAuthResponse;
    this.http.post<any>(CCommonUrl.LOGIN, {
      username,
      password
    }, { observe: 'response' }).subscribe((res) => {
      // console.log(res.json);
      console.log(res.headers);
      console.log(res.headers.get('Authorization'));
      accessToken.Authorization = res.headers.get('Authorization');
    });
    return of(accessToken);

界面

export interface IServerAuthResponse {
  Authorization: string;
}

现在 console.log 正在显示令牌,但我无法将值分配给 accessToken.Authorization。代码失败并出现以下错误

core.js:7187 ERROR TypeError: Cannot set property 'Authorization' of undefined at SafeSubscriber._next (auth.service.ts:60)

任何见解都会有所帮助

编辑:我只需要在界面中获取值。由于令牌即将进入 header 因此我无法将其直接映射到接口 ]

Edit2:就重复而言,该问题有 class 但在这种情况下它的界面

接口不是对象的实例,因此您需要像

一样初始化对象
let accessToken: IServerAuthResponse = {Authorization: ''};

然后你可以使用这一行

accessToken.Authorization = res.headers.get('Authorization');

需要先初始化accessToken变量。

export interface IServerAuthResponse {
  Authorization?: string;
}

let accessToken: IServerAuthResponse = {}

...
}, { observe: 'response' }).subscribe((res) => {
      // console.log(res.json);
      console.log(res.headers);
      console.log(res.headers.get('Authorization'));
      accessToken['Authorization'] = res.headers.get('Authorization');
    });