【问题标题】:At click route to details of given object单击路径到给定对象的详细信息
【发布时间】:2022-01-05 16:16:09
【问题描述】:

我有两个组件:recipe 和 recipe-detail。 Recipe 正在显示我的数据库中的食谱列表,并且 recipe-detail 应该显示给定食谱的详细信息。我想要实现的是,每当有人点击配方名称时,我想将他路由到配方详细信息组件。 这是我的食谱 html:

<section class="columns">
    <div class="column" *ngFor="let recipe of RecipeList">
        <h2><a routerLink="recipes/{{recipe.Id}}" routerLinkActive="true">{{recipe.name}}</a></h2>
        <p>{{recipe.recipeBody}}</p>
    </div>
</section>  

我的路由文件:

{path:'recipes', component: RecipeComponent},
{path: 'recipes/:id', component: RecipeDetailsComponent}

还有我的食谱细节:

export class RecipeDetailsComponent implements OnInit {
  @Input() recipe! : any;
  constructor(private route: ActivatedRoute,
    private sharedService: SharedService) { }

  ngOnInit(): void {
    this.getRecipe();
  }
  
  getRecipe() : void{
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);
  }
}

用于测试的简单 html:

<h2>Name : {{recipe.name}}</h2>
<h2>RecipeBody: {{recipe.recipeBody}}</h2>
<h2>IntendedUse: {{recipe.IntendedUse}}</h2>
<h2>CoffeeId: {{recipe.coffeeId}}</h2>

结果: 当我点击食谱名称(recipe.component)时,它会将我重定向到: http://localhost:4200/recipes/recipes 例如 http://localhost:4200/recipes/1

在控制台中我得到:TypeError: Cannot read properties of undefined (reading 'name')

编辑: 我如何获取它:

getRecipes() : Observable<any[]> {
    return this.http.get<any>(this.ApiUrl + '/Recipes')
  }
  getRecipeById(val:any){
    return this.http.get<any>(this.ApiUrl + '/Recipes/', val);
  }

【问题讨论】:

  • 你看到 id 被传递给 this.sharedService.getRecipeById(id).subscribe 了吗?请确认
  • @ShashankVivek 我已将我的方法切换为您的方法,在调试中我得到:const id = "recipes"。我猜是因为我还有localhost:4200/recipes/recipes url

标签: javascript html angular typescript rxjs


【解决方案1】:

我建议通过订阅如下方式进行操作

HTML

<h2><a [routerLink]="['/recipes', recipe.Id]" routerLinkActive="true">{{recipe.name}}</a></h2>


import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute,private sharedService: SharedService) {

ngOnInit() {
 this.route.params
      .subscribe(
        (params: Params) => {
         this.sharedService.getRecipeById(params['id']).subscribe(recipe => {
            this.recipe = recipe;
          })
        }
      );
    }
}

甚至使用switchMap 让它变得更好

【讨论】:

  • 我已将我的方法切换为您的方法,在调试中我得到:const id = "recipes"。我猜是因为我还有 localhost:4200/recipes/recipes 网址。如何解决该路由问题?
  • @Griefing:检查我答案中的 HTML 代码并告诉我
【解决方案2】:

您需要使用 = 来分配值,而不是 ==。

发件人:

this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);

收件人:

this.sharedService.getRecipeById(id).subscribe((recipe:any) => this.recipe = recipe);

【讨论】:

  • 哦该死的错字。有点?现在可以工作但仍然不确定(读取“名称”)
  • 使用 console.log(recipe) 来检查它的值。
  • 显示未定义
  • 这就是为什么你不能得到它的名字,它需要是一个json对象@Griefing
  • 我以与列表相同的方式获取它,所以我看不出有问题
猜你喜欢
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
相关资源
最近更新 更多