【问题标题】:Accessing route parameters - angular 8访问路由参数 - 角度 8
【发布时间】:2020-01-27 20:24:19
【问题描述】:

嘿,尝试用产品构建网站,但我无法从 productsComponent 获取数据到 ProductDetailsComponent。请帮帮我。

在我的 Product.ts 我有:

    export class Product {
  id: number;
  name: string;
  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }
}

在我的 ProductsComponenet 中,我有:

    import { Component } from '@angular/core';
import { Product } from '../services.service';

@Component({
  selector: 'app-services',
  templateUrl: './services.component.html',
  styleUrls: ['./services.component.css']
})
export class ServicesComponent {
  public products: Product[] = [
    new Product(1, "Product 001"),
    new Product(2, "Product 002"),
    new Product(3, "Product 003"),
    new Product(4, "Product 004"),
    new Product(5, "Product 005"),
    new Product(6, "Product 006"),
    new Product(7, "Product 007"),
    new Product(8, "Product 008")
  ];
}

在我的 ProductDetailComponent 中:

    import {Component, OnInit} from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Product } from '../services.service';



@Component({
  selector: 'app-detail-service',
  templateUrl: './detail-service.component.html',
  styleUrls: ['./detail-service.component.css']
})
export class DetailServiceComponent implements OnInit {

  public products: Product[] = [
    new Product(1, "Product 001"),
    new Product(2, "Product 002"),
    new Product(3, "Product 003"),
    new Product(4, "Product 004"),
    new Product(5, "Product 005"),
    new Product(6, "Product 006"),
    new Product(7, "Product 007"),
    new Product(8, "Product 008")
  ];
  product: Product = this.products[0];

  constructor(private routes: ActivatedRoute) {}
  ngOnInit() {
    this.routes.params.subscribe(params => {
      this.products.forEach((p: Product) => {
        if (p.id === params.id) {
          this.product = p;
        }
      });
    });
  }
}

我在 products.html 中显示所有产品,在我单击任何产品后,它会使用我的产品呈现我的 productdetails.html,但不显示正确的名称和 ID。 IT 在每个产品中显示第一个,但链接与产品的 id 是正确的。请帮忙。实在想不通是怎么回事。

【问题讨论】:

  • 我建议添加一个服务来抽象获取/设置/查找产品。
  • 您能发布您为此模块创建的路线吗?
  • 我的路线是: const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, {路径:'product/:id',组件:DetailServiceComponent },];
  • 通过尝试使用 params.get('id') 而不是 params.id 来访问 id 可能是一个远景。还尝试将 this.routes.params 订阅移动到构造函数。

标签: angular routes angular8 route-parameters


【解决方案1】:

要直接解决您的问题,您需要执行以下操作:

this.route.paramMap.subscribe(params => {
   let id = params.get('id');
   this.product = this.products.find(product => product.id === +id);
})

注意路由参数总是字符串,所以在上面的sn-p中,我在find方法中将id转换为数字。

不过,我建议您完全避免显式订阅。下面,我描述了一个更易于维护的实现,它更接近于响应式范式,并包含了一个工作的 stackblitz 示例。

您可以通过管道连接到 paramMap observable 以获取您的路由参数,使用 switchMap 运算符订阅它,并使用产品服务通过 id 获取产品。

您的 product-detail.component.ts 如下所示:

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {

  product$: Observable<any>;

  constructor(
    private route: ActivatedRoute,
    private productService: ProductService
  ) { }

  ngOnInit() {
    this.product$ = this.route.paramMap.pipe(
      switchMap(params => {
        let id = params.get('id');
        return this.productService.getProductById(+id);
      })
    )
  }

}

请注意,pipe 在我们订阅它之前不会执行。我们应该为此使用async 管道。所以你的 product-detail.component.html 应该是这样的:

<div class="product-detail-wrapper" *ngIf="product$ | async as product">
  <h3>Product Detail</h3>
  <p>Product ID: {{ product.id }}</p>
  <p>Product Name: {{ product.name }}</p>
</div>

有关工作示例,请查看此stackblitz

【讨论】:

  • 非常感谢。这个解决方案帮助了我!
  • @valery 太棒了!很高兴为您提供帮助!
猜你喜欢
  • 2021-11-12
  • 1970-01-01
  • 2018-05-17
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多