架构设计思路
- 数据结构设计:定义一个商品数据的接口,包含基本信息、价格、库存、促销活动等属性。
- 用户角色管理:在应用中维护一个表示当前用户角色的状态,可通过服务获取当前用户角色。
- 指令实现:创建一个指令,用于检测库存是否低,并为商品展示添加特殊样式。
- 管道实现:创建一个管道,用于格式化促销活动信息。
- 模板绑定:在商品展示的模板中,结合指令和管道来实现对应功能,根据用户角色展示不同价格。
关键代码示例
- 商品数据接口
export interface Product {
id: number;
name: string;
basePrice: number;
stock: number;
promotion: string;
}
- 用户角色服务
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserRoleService {
private userRole: 'normal' | 'vip' = 'normal';
setUserRole(role: 'normal' | 'vip') {
this.userRole = role;
}
getUserRole(): 'normal' | 'vip' {
return this.userRole;
}
}
- 库存低指令
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appLowStockStyle]'
})
export class LowStockStyleDirective implements OnInit {
@Input('appLowStockStyle') threshold: number = 10;
constructor(private el: ElementRef) { }
ngOnInit() {
// 假设从商品数据中获取库存
const stock = 0; // 实际需从商品对象获取
if (stock <= this.threshold) {
this.el.nativeElement.style.color ='red';
this.el.nativeElement.style.fontWeight = 'bold';
}
}
}
- 促销活动管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'promotionFormat'
})
export class PromotionFormatPipe implements PipeTransform {
transform(value: string): string {
// 示例格式化:将促销信息首字母大写
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
- 商品展示模板
<div *ngFor="let product of products" [appLowStockStyle]="5">
<h3>{{ product.name }}</h3>
<p *ngIf="userRoleService.getUserRole() === 'normal'">价格: {{ product.basePrice }}</p>
<p *ngIf="userRoleService.getUserRole() === 'vip'">价格: {{ product.basePrice * 0.9 }}</p>
<p>库存: {{ product.stock }}</p>
<p>促销活动: {{ product.promotion | promotionFormat }}</p>
</div>
- 组件代码
import { Component, OnInit } from '@angular/core';
import { UserRoleService } from './user-role.service';
@Component({
selector: 'app-product-display',
templateUrl: './product-display.component.html',
styleUrls: ['./product-display.component.css']
})
export class ProductDisplayComponent implements OnInit {
products: Product[] = [
{ id: 1, name: '商品1', basePrice: 100, stock: 5, promotion: '限时折扣' },
{ id: 2, name: '商品2', basePrice: 200, stock: 15, promotion: '满减优惠' }
];
constructor(private userRoleService: UserRoleService) { }
ngOnInit() {
this.userRoleService.setUserRole('vip'); // 示例设置用户角色
}
}