MST
星途 面试题库

面试题:Angular指令与管道结合在复杂业务场景下的架构设计与实现

假设要开发一个电商平台的商品展示模块,商品数据包含基本信息、价格、库存、促销活动等复杂内容。需要使用Angular指令与管道结合实现以下功能:根据不同的用户角色(普通用户、VIP用户)展示不同的价格(例如VIP用户看到的价格是普通用户价格的9折),同时库存低时通过指令给商品展示添加特殊样式,并且促销活动信息需要通过管道进行格式化展示。请阐述整体的架构设计思路,并给出关键代码示例。
16.2万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

架构设计思路

  1. 数据结构设计:定义一个商品数据的接口,包含基本信息、价格、库存、促销活动等属性。
  2. 用户角色管理:在应用中维护一个表示当前用户角色的状态,可通过服务获取当前用户角色。
  3. 指令实现:创建一个指令,用于检测库存是否低,并为商品展示添加特殊样式。
  4. 管道实现:创建一个管道,用于格式化促销活动信息。
  5. 模板绑定:在商品展示的模板中,结合指令和管道来实现对应功能,根据用户角色展示不同价格。

关键代码示例

  1. 商品数据接口
export interface Product {
  id: number;
  name: string;
  basePrice: number;
  stock: number;
  promotion: string;
}
  1. 用户角色服务
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;
  }
}
  1. 库存低指令
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';
    }
  }
}
  1. 促销活动管道
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);
  }
}
  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>
  1. 组件代码
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'); // 示例设置用户角色
  }
}