我有角度的服务,我使用httpClient,我有两个组件,卡车和编辑卡车,编辑卡车是我应该执行保存或更新操作,但现在当我从卡车html点击我的编辑按钮在卡车组件我没有得到任何响应,我使用表格进行验证,我如何从卡车组件调用编辑表单组件中的表单,以便我可以用实体填充表单
socket?.Dispose();
我的卡车组件
service
getTruckById(truckId: string): Observable<Truck> {
let cpParams = new URLSearchParams();
cpParams.set('id', truckId);
return this.http.get(this.baseUrl + "/" + cpParams)
.pipe(map(this.extractData),
catchError(this.handleError));
}
这个操作应该在下面的另一个组件中填充一个表单是组件和表单,我是新的角度所以我可能会有一些错误,请提出任何建议
export class TrucksComponent implements OnInit {
statusCode: number;
trucks: Observable<Array<Truck>>;
constructor(private truckService: TruckService, private router: Router) { }
ngOnInit() {
this.trucks = this.getTrucksDtos();
}
getTrucksDtos() {
return this.truckService.getTrucks();
}
deleteTruck(truck) {
this.truckService.deleteTruckById(truck.truckId)
.subscribe(successCode => {
this.statusCode = successCode;
// this.getTrucksDtos();
},
errorCode => this.statusCode = errorCode);
}
// i should get the truck from the service getbyid here then transfer to edits form
updateTruck(truckId: string) {
here i should do getby id
this.truckService.getTruckById(truckId)
this.router.navigate(['/edits'])
}
这是卡车组件卡车html的一部分
export class EditTruckComponent implements OnInit {
private truck: Truck;
public truckForm: FormGroup;
constructor(private truckService: TruckService, formBuilder: FormBuilder,
private router: Router) {
this.truckForm = formBuilder.group({
truckCode: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(30)]],
purchasedDate: ['', [Validators.required]],
descriptions : ['', [Validators.required]]
});
}
// private readonly toastCtrl: ToastController
ngOnInit() {
this.truck = this.truckService.getter();
}
processForm() {
if (this.truck == undefined) {
this.truckService.createTruck(this.truck)
.subscribe((truck) => {
console.log(truck)
this.router.navigate([''])
},(error) => {
console.log(error);
});
} else {
this.truckService.updateTrucks(this.truck)
.subscribe(
(truck) => {
console.log(truck);
this.router.navigate([''])
}, (error) => {
console.log(error);
});
}
}
hasError(field: string, error: string) {
const ctrl = this.truckForm.get(field);
return ctrl.dirty && ctrl.hasError(error);
}
isInvalidAndDirty(field: string) {
const ctrl = this.truckForm.get(field);
return !ctrl.valid && ctrl.dirty;
}
答案 0 :(得分:0)
您可以使用ActivatedRoute解决此问题:
第1步:[routing.ts]
const routes = [ { path: 'edit/:id', component: EditTruckComponent }, ... ]
导航时第2步:[TrucksComponent.ts]
updateTruck(truckId) { this.router.navigate([`/edits/${truckId}`])
第3步:[EditTruckComponent.ts]我们需要使用ActivatedRoute形式@ angular / router
contructor( ..., private route: ActivatedRoute, ... ) { }
第4步:[EditTruckComponent.ts]从网址获取ID
ngOnint() { this.route.params.subscribe((param)) => { console.log(param['id']; }
第5步:现在您在[EditTruckComponent]中获取了id,使用param ['id']调用服务;
this.truckService.getTruckById(param['id']).subscribe(...);