角度路由数据

时间:2017-11-30 15:47:28

标签: angular routing routes

我有一个小问题。我想将数据从我的产品传递到我的单个产品页面。所以我有一个产品页面,其中包含10-15种产品,包括产品标题,小描述,图片和更多信息按钮。当我点击该按钮时,我想重定向到该产品页面。所以它说localhost:4200 / product / productTitle1,它的图片,描述和标题可以在{{title}}这个页面上使用。

所以我有产品component.html

<div *ngFor="let product of productList.products" class="col-sm">
 <div class="card mt-5" style="width: 20rem;">
  <div class="card-body">
    <h4 class="card-title">{{ product.title }}</h4>
    <h6 class="card-subtitle mb-2 text-muted">{{ product.subtitle }}</h6>
    <img [src]="product.imageUrl" class="card-text img-fluid">{{ product.cardText }}<br>
    <a [routerLink]="['/product', product.title]" class="card-link btn btn-outline-primary btn-sm mt-3">More info</a>
    <a href="#" class="card-link btn btn-info btn-sm mt-3">Add to cart</a>
  </div>
</div>

使用 routerLink 在链接中显示产品标题并将我重定向到他的产品信息页面

[routerLink]="['/product', product.title]

这里是单个product.component.ts

export class ProductComponent implements OnInit{
  title: string;
  subtitle: string;
  cardText: string;

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

ngOnInit() {
  let params = this.route.snapshot.paramMap;
  this.title  = params.get('title');
  this.subtitle  = params.get('subtitle');
  this.cardText = params.get('cardText');
 }
}

product.service.ts ,其中包含所有产品信息。

@Injectable()
export class ProductService {
  products: any[] = [
{
  id: 1,
  title: 'Some title',
  subtitle: 'Some subtitle',
  imageUrl: './assets/images/main-image.jpg',
  cardText: 'Some descriptive text'
},
{
  id: 2,
  title: 'Some title about second product',
  subtitle: 'Some subtitle 2',
  imageUrl: './assets/images/prod-cop.png',
  cardText: 'Some text'
}, ...

问题是,除了{{ title }}之外,我无法在单个产品页面上看到有关该产品的任何信息。但是我注意到,如果我这样输入routerLink =['/product', product]我可以使用快照访问所有信息,但链接也将包含所有信息,这看起来很糟糕。 我仍然是Angular的初学者,所以我需要你的帮助。

3 个答案:

答案 0 :(得分:1)

由于您已经拥有服务,因此您无需从路由传递数据。只需从路线参数中获取产品ID,然后从产品服务中找到产品

export class ProductComponent implements OnInit{
 product: any;

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

ngOnInit() {
  const productId = route.snapshot.params['productId'];
  this.product = this.prodcutList.products.find((product)=>{
   return product.id === productId
   });
 }
}

现在生成链接

 <a [routerLink]="['/product']" [queryParams]="{productId: product.id}">More info</a>

您的ProductComponent HTML模板现在可以使用产品对象

答案 1 :(得分:0)

您需要在网址[routerLink]="['/product', product.id]中传递ID,然后通过在单个产品页面中调用getProductById(id)来为您的服务添加新方法

答案 2 :(得分:0)

如果要隐藏路线中显示的信息,可以使用skipLocationChange标志,如下所示

this.router.navigateByUrl("/product/"+id,{skipLocationChange:true});
相关问题