我正在尝试构建一个用于订购电影的“快速订购”组件。
第一个元素是“选择”。我通过 http 请求获取结果,然后呈现选项。
当用户选择电影选项时,我需要向他显示另一个显示可用日期的选项。我需要根据以字符串日期作为键的对象呈现选择。
例如:
{
"2018-07-19": {
"00:10": "5b4f445da2c93e36c4f1a1ca",
"01:00": "5b4f355ab6334b27fc031adb",
"13:44": "5b4f43fda2c93e36c4f1a1c9"
},
"2018-07-25": {
"23:00": "5b4f357db6334b27fc031adc"
}
}
在渲染 movieList 选择和检索日期对象时一切正常。但是当我添加第二个选择 (id=selectDate) 的 html 代码时,出现错误。
这是我的代码: :
import { Component, OnInit } from '@angular/core';
import { MoviesService } from '../services/movies.service';
import { ShowService } from '../services/show.service';
import { Observable } from 'rxjs';
import * as moment from 'moment';
@Component({
selector: 'app-quick-order',
templateUrl: './quick-order.component.html',
styleUrls: ['./quick-order.component.css']
})
export class QuickOrderComponent implements OnInit {
movieList: any;
movieShowsSchedule: any;
selectedMovie: any;
selectedDate: any;
constructor(private moviesService: MoviesService, private showService: ShowService) { }
ngOnInit() {
this.movieList = this.moviesService.getMovies();
}
onChangeSelectMovie() {
this.movieShowsSchedule = this.showService.getMovieSchedule(this.selectedMovie).subscribe(res => {
alert("we got movie successfully");
console.log(res);
}, err => {
alert("we did not get movie");
});
}
onChangeSelectDate() {
}
}
html:
<div class="form-group">
<label for="selectMovie">Movie:</label>
<select id="selectMovie" [(ngModel)]="selectedMovie" (change)="onChangeSelectMovie()">
<option *ngFor="let movie of movieList | async" value="{{movie._id}}" >{{movie.title}} </option>
</select>
<label for="selectDate">Date:</label>
<select id="selectDate" [(ngModel)]="selectedDate" (change)="onChangeSelectDate()">
<option *ngFor="let date in movieShowsSchedule | async" value="{{date}}" >{{date}}</option>
</select>
</div>
有人知道是什么问题吗?以及如何使这段代码起作用? 非常感谢!
最佳答案
有几个问题。
- 由于您使用的是
async
, 你应该设置moveShowSchedule
对于 Observable 的结果而不是订阅,或者更简单,不要使用异步。 - 您可以使用
map
将 movieShowSchedule 转换为您 View 的可用模型。 - 您应该将
*ngFor
中的 in 替换为 of .
组件
movieShowsSchedule = [];
onChangeSelectMovie() {
this.showService.getMovieSchedule(this.selectedMovie).subscribe(x => {
this.moveShowSchedule = [];
for (let key in x) {
this.moveShowSchedule.push({ key, date: x[key].date });
}
});
}
HTML
<option *ngFor="let x of movieShowsSchedule" [ngValue]="x.date">
{{x.date}}
</option>
我不想重构你的整个代码,但如果你创建了一个绑定(bind)到更改事件的 Observable,你就可以使用 switchMap 来更新 movieShowSchedule Subject。
关于javascript - Angular 6 : trying loop throw an object (via *ngFor) after choosing a value of a 'select' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51405998/