MST

星途 面试题库

面试题:Angular插值表达式在动态组件与服务交互场景下的数据显示优化

在一个Angular项目中,有一个动态加载的组件,该组件依赖于一个服务获取数据。数据是不断变化的实时数据。请阐述如何利用插值表达式实现数据的实时显示,并且要考虑到性能优化,避免不必要的视图更新。例如,服务返回的是一个包含多个股票实时价格的数组,如何在组件视图中高效地通过插值表达式显示这些价格,同时确保当某个股票价格变化时,仅更新对应的视图部分。
19.2万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 创建服务获取实时数据
    • 首先创建一个服务,用于获取实时股票数据。假设服务名为 StockService,在服务中使用 BehaviorSubjectReplaySubject 来管理数据的变化。
    • 例如:
    import { Injectable } from '@angular/core';
    import { Observable, BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class StockService {
      private stockPricesSubject = new BehaviorSubject<number[]>([]);
      public stockPrices$: Observable<number[]> = this.stockPricesSubject.asObservable();
    
      constructor() {
        // 模拟实时更新数据,例如通过定时器
        setInterval(() => {
          const newPrices = [Math.random() * 100, Math.random() * 100, Math.random() * 100];
          this.stockPricesSubject.next(newPrices);
        }, 3000);
      }
    }
    
  2. 动态加载组件
    • 在需要动态加载组件的父组件中,使用 ComponentFactoryResolver 来动态加载组件。
    • 例如:
    import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
    import { StockComponent } from './stock.component';
    
    @Component({
      selector: 'app - parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent {
      @ViewChild('stockPlaceholder', { read: ViewContainerRef }) stockPlaceholder: ViewContainerRef;
    
      constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    
      ngOnInit() {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(StockComponent);
        const componentRef = this.stockPlaceholder.createComponent(componentFactory);
      }
    }
    
    • parent.component.html 中添加:
    <ng - template #stockPlaceholder></ng - template>
    
  3. 在动态加载组件中使用插值表达式并优化性能
    • 在动态加载的 StockComponent 中,订阅服务的数据并使用插值表达式显示数据。
    • 为了避免不必要的视图更新,使用 ChangeDetectionStrategy.OnPush
    • 例如:
    import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
    import { StockService } from './stock.service';
    import { Observable } from 'rxjs';
    
    @Component({
      selector: 'app - stock',
      templateUrl: './stock.component.html',
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class StockComponent implements OnInit {
      stockPrices$: Observable<number[]>;
    
      constructor(private stockService: StockService) {}
    
      ngOnInit() {
        this.stockPrices$ = this.stockService.stockPrices$;
      }
    }
    
    • stock.component.html 中:
    <div *ngFor="let price of stockPrices$ | async; let i = index">
      Stock {{i + 1}} Price: {{price}}
    </div>
    
    • 这里使用 async 管道订阅 Observable,并且 ChangeDetectionStrategy.OnPush 会使得组件仅在输入属性或 Observable 有新值时更新视图。由于数组中的每个价格是独立的,当某个价格变化时,Angular 的 OnPush 策略结合 async 管道会确保仅更新对应的 ngFor 循环中的视图部分,从而实现性能优化。