面试题答案
一键面试- 创建服务获取实时数据
- 首先创建一个服务,用于获取实时股票数据。假设服务名为
StockService
,在服务中使用BehaviorSubject
或ReplaySubject
来管理数据的变化。 - 例如:
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); } }
- 首先创建一个服务,用于获取实时股票数据。假设服务名为
- 动态加载组件
- 在需要动态加载组件的父组件中,使用
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>
- 在需要动态加载组件的父组件中,使用
- 在动态加载组件中使用插值表达式并优化性能
- 在动态加载的
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
循环中的视图部分,从而实现性能优化。
- 在动态加载的