angular - 如何导航到 Angular 中创建的项目
问题描述
我正在添加一个新食谱。之后我想导航到新添加的食谱。
我应该如何传递创建的食谱的 ID?
我试过:this.router.navigate(['/recipe/edit/' + id]);
但它并没有把我导航到那里。作为回应,我得到: http://localhost:5000/api/recipes/%7Bid%7D 400(错误请求)
this.router.navigate(['/recipe/edit/HERE MUST BE ID CREATED RECIPE']);
我的 add-recipe.component.ts
@Component({
selector: 'app-add-recipe',
templateUrl: './add-recipe.component.html',
styleUrls: ['./add-recipe.component.css']
})
export class AddRecipeComponent implements OnInit {
categories: Category[];
user: User;
recipe: Recipe;
addRecipeForm: FormGroup;
constructor(private fb: FormBuilder,
private alertifyService: AlertifyService,
private router: Router,
private recipeService: RecipeService, private authService: AuthService) { }
ngOnInit() {
this.createRecipeForm();
this.getCategories();
}
createRecipeForm() {
this.addRecipeForm = this.fb.group({
name: ['', Validators.required],
ingredients: ['', Validators.required],
preparationTime: ['', Validators.required],
description: ['', Validators.required],
categoryId: ['', Validators.required]
});
}
createRecipe(id: number) {
if (this.addRecipeForm.valid) {
this.recipe = Object.assign({}, this.addRecipeForm.value);
this.recipeService.addNewRecipe(this.authService.currentUser.id, this.recipe).subscribe(() => {
this.alertifyService.success('New recipe has been added!');
}, error => {
this.alertifyService.error(error);
}, () => {
this.router.navigate(['/recipe/edit/']);
});
}
}
cancel() {
this.router.navigate(['members']);
this.alertifyService.warning('Cancelled');
}
解决方案
您必须在服务中获取已id
创建项目response
的addNewRecipe
。这是您应该导航的方式:
this.recipeService.addNewRecipe(this.authService.currentUser.id, this.recipe)
.subscribe((result) => {
this.alertifyService.success('New recipe has been added!');
let id = result.id;
this.router.navigate([`/recipe/edit/${id}`]);
}, error => {
this.alertifyService.error(error);
});
推荐阅读
- html - 在有两个标题的表格中,主标题不会在滚动时保持粘性
- python - 如何改变盒子的不透明度(cv2.rectangle)?
- java - 如何修复:java.lang.ClassCastException:androidx.appcompat.widget.AppCompatTextView 无法转换为 android.widget.Button
- python-3.x - 循环遍历 csv 数据
- ios - defer 语句的不同行为
- node.js - 如何使用 ckeditor 在 mongoose-node 应用程序中上传图像。文件将上传到 s3
- qt - 使用 QMediaplayer 从缓冲区播放视频并在视频播放时附加缓冲区
- c# - 从字符串中删除 HTML -- 注释
- ios - 我可以使用 Siri Shortcut 更改变量的值吗?
- javascript - 为什么我的 add like 方法返回“无法读取未定义的属性”?