【发布时间】: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