【问题标题】:Cannot assign to 'GetUserByIdModel' because it is not a variable无法分配给“GetUserByIdModel”,因为它不是变量
【发布时间】:2019-06-11 09:12:23
【问题描述】:

我正在尝试填充模型,但收到错误无法分配给“GetUserByIdModel”,因为它不是变量。

这是我的模特

export class GetUserByIdModel {
  firstname: string;
  lastname: string;
  nationalityId: number;
  identityTypeId: number;
  identityValue: string;
  titleId: number;
  genderId: number;
  contactChannels: Array<ContactChannel>;
}

export class ContactChannel {
  type: number;
  value: string;
}

然后我将其导入服务文件并尝试使用它

声明

userDetails: GetUserByIdModel;

功能

  getUserDetails(userId): Observable<GetUserByIdModel> {l
    const token = this._storeService.getStoredData().id_token;
    const headers = new HttpHeaders()
      .set('Authorization', `Bearer ${token}`)
      .set('Content-Type', 'application/json');
    const options = { headers: headers };
    const url = `${this.candidateUrl}/Get/${userId}`;
    this._http.get<any>(url, options).subscribe((resp) => {
    this.userDetails: GetUserByIdModel = {
      firstname: resp.firstname,
      lastname: resp.lastname,
      nationalityId: resp.firstname,
      identityTypeId: resp.identityTypeId,
      identityValue: resp.identityValue,
      titleId: resp.titleId,
      genderId: resp.genderId,
      contactChannels: [
        { type: 1, value: resp[0].value },
        { type: 2, value: resp[1].value }
      ],
    };
  })

    return new Observable((observer) => {
      observer.next(this.userDetails);
      observer.complete();
    });
  }

我在这一行看到错误this.userDetails: GetUserByIdModel = {...

请帮忙

【问题讨论】:

  • 尝试将this._http.get&lt;any&gt;更改为this._http.get&lt;GetUserByIdModel&gt;
  • 试过了,还是一样的错误:(
  • 使类中的所有字段都可以为空。喜欢名字?:字符串;姓氏?:字符串;在 ContactChannel 类中也相同或更好地使用接口而不是类

标签: angular typescript


【解决方案1】:

删除 this.userDetails: GetUserByIdModel -&gt; this.userDetails = {..} 的类型,因为它已经在声明中,并使字段可以为空 firstName?, lastName?...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2020-01-15
    相关资源
    最近更新 更多