【问题标题】:Angular - Cannot find a differ supporting object 'Item One' of type 'string'. NgFor only supports binding to Iterables such as ArraysAngular - 找不到“字符串”类型的不同支持对象“项目一”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2020-06-11 11:43:59
【问题描述】:

StackOverflow 上的几个问题与此类似,但找不到匹配的解决方案。

我的代码在尝试将项目获取到“选择”控件时工作正常,如果项目计数大于 1,我会得到成功的结果,但奇怪的是,如果返回的数据只包含一个项目,我会得到一个控制台错误指向对模板代码说:

找不到“字符串”类型的不同支持对象“项目一”。 NgFor 只支持绑定到 Arrays 等 Iterables。

这是我的 Html 代码:

      <mat-select [formControl]="itemControl" required [(value)]="itemValue">
        <mat-option>--</mat-option>
        <mat-option *ngFor="let item of items" [value]="item">{{item}}</mat-option>
      </mat-select>

组件:

export class LoginWithDbComponent implements OnInit, OnDestroy {
  . . .
  items: string[] = [];
  itemValue: string;

  constructor(
    . . .
    public authService: AuthService,
  ) {

  }

  login(): void {
    this.authService.login(this.getUserLogin()).subscribe(
      next => {
        this.getUserItems();
      },
      error => {
      . . .
    );    
  }

  getUserItems() {
    this.items= this.authService.userItems;
    return this.items|| []; 
  }

还有服务:

    export class AuthService {
      userItems: any = [];
      . . .
      login(model: any) {
        return this.http.post(this.baseUrl + 'login', model).pipe(
          map((response: any) => {
            const user = response;
            if (user) {
              this.decodedToken = this.jwtHelper.decodeToken(user.token);
              this.userItems = this.decodedToken['items'];
              console.log(this.userItems);              <--- shows 'Item One'
            }
          })
        );
      }
      . . .
    }

那么对于这种特殊情况应该怎么做呢?

【问题讨论】:

  • decodedToken 后能否在 AuthService 中显示 userItems 值?问候
  • @CharlySosa,在 decodedToken 正确显示 userItems 值之后,AuthService 中的 console.log(this.userItems):'Item One',请让我更新问题。
  • 当只有一个项目时,对“post”调用的响应中的“items”标记似乎不是一个数组。您可能需要检查this.decodedToken['items'] 是否为数组,如果不是,则将单个字符串添加到数组中。

标签: html angular typescript


【解决方案1】:

当只有一个项目时,对您的“发布”调用的响应中的“项目”标记似乎不是一个数组。您可能需要检查this.decodedToken['items'] 是否为数组,如果不是,则将单个字符串添加到数组中。

let itemsToken = this.decodedToken['items'];
this.userItems = Array.isArray(itemsToken) ? itemsToken : [itemsToken];

【讨论】:

  • 是的,你是对的,我已经从 Postman 手动解码了令牌,当只有一个项目时,它变成了一个字符串而不是一个数组。你的小费就像一个魅力,非常感谢安德鲁 :)
猜你喜欢
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 2019-04-04
  • 2020-10-17
  • 2017-10-15
  • 2018-07-19
相关资源
最近更新 更多