面试题答案
一键面试- 配置路由模块:
- 在
app - routing.module.ts
中,首先定义产品详情页的主路由,例如:
const routes: Routes = [ { path: 'product/:productId', component: ProductDetailComponent, children: [ { path:'specification', component: ProductSpecificationComponent }, { path:'review', component: ProductReviewComponent } ] } ];
- 这里
product/:productId
定义了产品详情页的路由,并通过:productId
捕获产品ID参数。children
数组定义了嵌套路由,分别是specification
和review
。
- 在
- 传递其他参数:
- 如果还需要传递用户ID等其他参数,可以通过
queryParams
。在导航到产品详情页时,可以这样传递参数:
this.router.navigate(['/product', productId], { queryParams: { userId: this.userId } });
- 在目标组件(如
ProductDetailComponent
及其子组件)中获取参数:
import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) {} ngOnInit() { const productId = this.route.snapshot.paramMap.get('productId'); const userId = this.route.snapshot.queryParamMap.get('userId'); }
- 如果还需要传递用户ID等其他参数,可以通过
- 确保导航准确性和数据一致性:
- 导航准确性:
- 使用
routerLink
指令在模板中创建链接,确保路径拼写正确。例如:
<a [routerLink]="['/product', productId,'specification']">产品规格</a> <a [routerLink]="['/product', productId,'review']">产品评论</a>
- 对于编程式导航,使用
this.router.navigate
时,确保传递的参数和路径准确无误。
- 使用
- 数据一致性:
- 可以使用服务(Service)来共享数据。例如,创建一个
ProductDataService
,在产品详情页组件及其子组件中注入该服务。
@Injectable({ providedIn: 'root' }) export class ProductDataService { private product: Product; setProduct(product: Product) { this.product = product; } getProduct() { return this.product; } }
- 在
ProductDetailComponent
中获取产品数据后,调用setProduct
方法存储数据,子组件(如ProductSpecificationComponent
和ProductReviewComponent
)通过注入ProductDataService
并调用getProduct
方法获取相同的数据,保证数据一致性。
- 可以使用服务(Service)来共享数据。例如,创建一个
- 导航准确性: