我创建了一个自动完成控件,其中http api
获取数据。
但是<mat-option *ngFor="let region of regions" [value]="region.name">
抛出这样的错误:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我已经检查了Region[]
第52行中的数据返回method 1
。
我用Google搜索解决方案method 2
,它可以工作,但不能与loading indicator
一起工作
我希望有人可以帮助我。谢谢。
我的代码:https://stackblitz.com/edit/angular-89p1pm
我有3个问题要问:
Observable with loading indicator
form.get('region').valueChanges.pipe(
debounceTime(300),
tap(r => this.isLoading = true),
switchMap(inputCountry =>
this.regionService.getRegions().pipe(
map( regions => {
return regions.filter(region => region.name.indexOf(inputCountry) >= 0)
})
)
)
).subscribe(data => {
console.log('onRegionChanged: data', data);
this.isLoading = false;
this.regions = data;
})
form.get('region').valueChanges.pipe(
debounceTime(300),
tap(r => this.isLoading$.next(true)),
).subscribe(inputCountry => {
this.regions$ = this.regionService.getRegions().pipe(
tap(r => this.isLoading$.next(false)),
map(regions => regions.filter(region => region.name.indexOf(inputCountry) >= 0))
)
});
答案 0 :(得分:1)
您的问题是您要遍历一个空数组。只需将其添加到您的条件即可。
<template>
<div class="container join-form">
<form>
<div class="container">
<h2>Join to session</h2>
</div>
<div class="form-group">
<label for="sessionId">Session ID:</label>
<input v-model="sessionId" class="form-control" type="text" name="sessionId" placeholder="Session ID">
</div>
<div class="form-group">
<label for="userName">Username:</label>
<input v-model="userName" class="form-control" type="text" name="userName" placeholder="Your name">
</div>
<button v-on:click.prevent="joinSession()" class="btn btn-primary">Join session</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
userName: "",
sessionId: this.$route.params.sessionId,
userId: null
};
},
methods: {
joinSession() {
this.$http
.post('/joinsession', {
userName: this.userName,
sessionId: this.sessionId
})
.then(
data => {
this.userId = data.body.userId;
this.$router.push("/user/" + this.sessionId + "/" + this.userId);
},
() => {
this.$router.push("/error");
}
);
}
}
};
</script>
<style>
.join-form {
width: 50%;
}
</style>