StackOverflow上的几个问题与此类似,但找不到匹配的解决方案。
当试图将项目提取到"Select"控件中时,我的代码运行良好,如果项目计数大于1,我会得到成功的结果,但奇怪的是,如果返回的数据只包含一个项目,我会收到一个控制台错误,指向模板代码并说:
找不到不同类型为"string"的支持对象"Item One"。NgFor只支持绑定到数组等可伸缩对象。
这是我的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'
}
})
);
}
. . .
}
那么,对于这种特殊的情况,什么应该起作用呢?
当只有一个项时,对"post"调用的响应中的"items"标记似乎不是数组。您可能需要检查this.decodedToken['items']
是否是数组,如果不是,请将单个字符串添加到数组中。
let itemsToken = this.decodedToken['items'];
this.userItems = Array.isArray(itemsToken) ? itemsToken : [itemsToken];