【问题标题】:Typescript: Unable to set value to interface property in Angular project [duplicate]打字稿:无法在Angular项目中为接口属性设置值[重复]
【发布时间】:2019-12-17 02:33:18
【问题描述】:

我正在研究 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 错误类型错误:无法设置属性“授权” 不明确的 在 SafeSubscriber._next (auth.service.ts:60)

任何见解都会有所帮助

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

Edit2:就重复而言,该问题具有类,但在这种情况下它的接口

【问题讨论】:

  • 因为accessToken没有初始化。
  • 您是否在任何地方创建了accessToken?你已经声明了它,但我认为它不会在任何地方实例化,除非我遗漏了什么。
  • AccessToken 未初始化导致问题。详见stackoverflow.com/a/23413375/9958058评论。另外,另一种方法是使用类而不是接口。

标签: angular typescript angular8


【解决方案1】:

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

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

然后你可以使用这条线

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

【讨论】:

    【解决方案2】:

    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');
        });
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2018-07-14
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2017-09-15
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多