
需求分析,我需要从点击每个商品显示每个商品的详情页,之前使用的是通过路由传商品名称,现在是通过传商品的id,在真实的开发中,也是通过传商品的id。在商品详情页面还可以看到评分等相关信息,如图所示

怎么满足这个需求??
1)首先我们需要定义一个productSerive的服务来封装商品列表和评分列表,需要定义3个方法getProducts(获取商品组件)、getProduct(获取商品id的)、getCommentsForProductId(获取评论id)
import { Injectable } from '@angular/core';
@Injectable()
export class ProductService {
private products:Product[] = [
new Product(1, "第一个商品", 1.99, 3.5, "今天很开心啊", ["电子产品"]),
new Product(2, "第二个商品", 1.99, 2.5, "今天很开心啊", ["电子产品"]),
new Product(3, "第三个商品", 1.99, 3.5, "今天很开心啊", ["图书设备"]),
new Product(4, "第四个商品", 1.99, 4.5, "今天很开心啊", ["电子产品"]),
new Product(5, "第五个商品", 1.99, 1.5, "今天很开心啊", ["日化用品"]),
new Product(6, "第六个商品", 1.99, 1.5, "今天很开心啊", ["日化用品"]),
];
private comments:Comment[] = [
new Comment(1,1,"2017-02-02 19:22:22","张三",3,"东西不错"),
new Comment(2,1,"2017-02-02 20:22:22","张三",3,"东西不错呀"),
new Comment(3,2,"2017-02-02 21:22:22","南蓝",2,"东西不错,下次再来"),
new Comment(4,2,"2017-02-02 24:22:22","南蓝小姐",4,"东西不错")
]
constructor() {
}
//得到商品组件
getProducts():Product[]{
return this.products;
}
//获取商品的id
getProduct(id:number):Product {
return this.products.find((product) => product.id == id);
}
//评论的id和传进来的id是相同的话,那么就把评论显示在页面上
getCommentsForProductId(id:number):Comment[] {
return this.comments.filter((comment:Comment) =>comment.productId == id);
}
}
export class Product {
constructor(public id:number,
public title:string,
public price:number,
public rating:number,
public desc:string,
public cateories:Array<string>) {
}
}
export class Comment{
constructor(public id:number, //评论的id
public productId:number, //商品的id
public timestamp: string, //时间
public user:string, //评论人
public rating:number, //星级评分
public content:string //评论的内容
) {
}
}
2)修改路由配置3步曲
a.在app.modules.ts修改路由配置
const routeConfig:Routes = [
{path:'',component:HomeComponent},
{path:'product/:productId',component:ProductDetailComponent}
]
b.product.component.ts的routerLink修改传值
<h4><a [routerLink]="['/product',product.id]">{{product.title}}</a></h4>
c.productdetail.component.ts修改参数快照
ngOnInit() {
//获取商品的id赋给临时的变量
let productId:number = this.routeInfo.snapshot.params["productId"];
}
3)注入服务ProductService并且使用
c.注入productService并且使用(在使用之前记得在app.modules.ts里面注入productService)

在详情页使用

与列表页不同的是,商品详情页多了评分,方法与使用商品列表是一样的方法
4)最后在productdetail.component.html绑定数据即可
<div class="thumbnail">
<img src="http://via.placeholder.com/350x150">
<div>
<h4 class="pull-right">{{product.price}}元</h4>
<h4>{{product.title}}</h4>
<p>{{product.desc}}</p>
</div>
</div>
<div>
<p class="pull-right"> {{comment.length}}</p>
<p><app-stars [rating]="product.rating"></app-stars></p>
</div>
<div class="well">
<div class="row" *ngFor="let comment of comments">
<hr>
<div class="col-md-12">
<app-stars [rating]="comment.rating"></app-stars>
<span class="pull-right">{{comment.timestamp}}</span>
<p>{{comment.user}}</p>
<p>{{comment.content}}</p>
</div>
</div>
</div>
网友评论