首页 > 解决方案 > 如何导航到 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');
  }

标签: angularroutes

解决方案


您必须在服务中获取已id 创建项目responseaddNewRecipe。这是您应该导航的方式:

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);
      }); 

推荐阅读