我有一个组件来创建或编辑Trips,我想使用相同的表单。如果有任何参数,我该如何提前检查?
ngOnInit() {
this.trip = this.fb.group({
id: '',
name: ['', [Validators.required, Validators.minLength(2)]],
});
this.route.paramMap
.switchMap((params: ParamMap) => this.tripService.getTrip(+params.get('id')))
.subscribe((trip: any) => {
this.trip.patchValue({
id: trip.id,
name: trip.name
});
})
}
我已经尝试过类似的事情,但没有成功
ngOnInit() {
this.trip = this.fb.group({
id: '',
name: ['', [Validators.required, Validators.minLength(2)]],
});
this.route.paramMap
.switchMap((params: ParamMap) => {
console.log(params.get('id'))
if(params.get('id')){
this.tripService.getTrip(params.get('id')).subscribe((trip: any) => {
this.trip.patchValue({
id: trip.id,
name: trip.name
});
})
}
}
)
}
答案 0 :(得分:3)
与此相似的事情:
this.route.paramMap
.filter(params => params.get('id') !== undefined)
.switchMap((params: ParamMap) => this.tripService.getTrip(+params.get('id')))
.subscribe((trip: any) => {
this.trip.patchValue({
id: trip.id,
name: trip.name
});
})
}