请求的路径包含索引1处未定义的段,无法正确传递id



我的Angular应用程序有一些问题。

简单解释一下,我创建了一个类型为FormInput的对象,它存储来自表单的所有数据。单击按钮后,我想执行两个操作:

  1. 保存FormInput对象和
  2. 用我刚刚创建的对象的id导航到一个新的页面。

我的代码保存对象,但是当我调用我的函数导航到另一个页面时,我传递的id是undefined。我不知道如何从当前创建的对象中正确获取id,并将其传递给导航函数。

@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
forminput: Forminput = new Forminput();
shops: Array<Shop> = [];
products: Array<Product> = [];
shop: Shop;
product: Product;
exampleForm: FormGroup;
submitted = false;
constructor( private formBuilder: FormBuilder, private formService: FormService, private router: Router){}
get f() { return this.exampleForm.controls; }
onSubmit() {
this.submitted = true;
if (this.exampleForm.invalid) {
return;
}
if (this.submitted)
{
this.save();
}
this.goToDocument(this.forminput.id);    // here it is undefined 
}
save() {
this.forminput.shopid = this.shop.id;
this.forminput.productid = this.product.id;
this.formService.createInputForm(this.forminput)
.subscribe(data => {
console.log(data);
},
error => console.log(error)
);
}
ngOnInit() {
this.exampleForm = this.formBuilder.group({
firstName: ['', [Validators.required]],
secondName: ['', [Validators.required]],
familyName: ['', [Validators.required]],
shop: ['', [Validators.required]],
products: ['', Validators.required]
});
this.getShops();
}
fireGetShopProducts(){
console.log(this.shop.id);
this.getShopProducts(this.shop.id);
}
getShopProducts(id: number){
this.formService.getShopProducts(id)
.subscribe(
(product: Array<Product>) => {
console.log(product);
this.products = product;
},
error => console.log(error)
);
}
getShops(){
this.formService.getListShops()
.subscribe(
(shops: Array<Shop>) => {
console.log(shops);
this.shops = shops;
},
error => {
console.log(error);
}
);
}
goToDocument(id: number){
this.router.navigate(['document', id]);
}
}
  1. 指定id的位置this.forminput?
  2. 看起来应该goToDocument()如果this.submitted真正=那么把这一行放到if里面,save()

谢谢你的回答。我解决了这个问题。我只是在save()函数中进行调用,它开始正常工作:

save() {
this.forminput.shopid = this.shop.id;
this.forminput.productid = this.product.id;
this.formService.createInputForm(this.forminput)
.subscribe((data: Forminput) => {
this.id = data.id;
this.goToDocument(this.id);
},
error => console.log(error)
);
}

然而,它仍然有点奇怪,因为如果从save()中删除this.goToDocument(this.id);行,并在调用save()后将其放入onSubmit()中,它停止工作。

相关内容

  • 没有找到相关文章

最新更新