我有个小问题。我想把数据从我的产品,到我的单一产品页面。因此,我有一个产品页面与10-15产品显示与产品的标题,小的描述,图片和按钮获得更多的信息。当我点击那个按钮时,我想被重定向到那个产品页面。因此它说localhost:4200/productTitle1 1,它的图片、描述和标题可以像{ title }一样在页面上使用。
所以我有products 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]这里是single 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],我可以使用快照访问所有信息,但是链接也会包含所有信息,这看起来很糟糕。我还是初学者,所以我需要你的帮助。
发布于 2017-11-30 15:53:56
由于您已经有了服务,所以不必从路由传递数据。只需从路线参数中获取产品标识,并从您的产品服务中找到产品。
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模板现在可以使用产品对象了。
发布于 2017-11-30 15:54:22
您需要在url [routerLink]="['/product', product.id]中传递id,并通过在单个产品页中调用id,在服务(如getProductById(id) )上添加一个新方法。
发布于 2017-11-30 15:55:35
如果要隐藏路由中显示的信息,可以使用skipLocationChange标志,如下所示
this.router.navigateByUrl("/product/"+id,{skipLocationChange:true});https://stackoverflow.com/questions/47577316
复制相似问题