如何通过Observables替代HTML模板直接调用函数并实现变量赋值?
用.subscribe()赋值变量解决Angular模板函数调用的性能问题
之前习惯在Angular HTML模板里直接调用函数,但这种做法会在每次变更检测时触发函数执行,影响渲染性能。尝试用服务的Observable赋值变量并订阅变化,但没成功。现有代码如下:
组件代码:
public getMaxUnit(){ return MaxUnits.Dollars; }
HTML模板:
<div style="display: flex;"> <table style="width:100%;"> <thead> <tr> <th>Max</th> </tr> </thead> <tbody> <tr *ngFor="let maxValue of maxValueTable"> <td> {{ maxValue | numberFormatter: getMaxUnit()}}</td> </tr> </tbody> </table> </div>
实现步骤:
在组件中定义变量和Observable
先声明存储单位值的变量,以及提供值的Observable(如果是从服务获取,直接使用服务返回的Observable即可):import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable, Subscription } from 'rxjs'; import { MaxUnits } from './your-path-to-max-units'; // 替换为实际路径 @Component({ selector: 'your-component', templateUrl: './your-component.html' }) export class YourComponent implements OnInit, OnDestroy { maxUnit!: string; // 存储单位值的变量 private maxUnitSubscription!: Subscription; // 订阅对象,用于销毁时取消订阅 // 如果从服务获取:private unitService: UnitService // 模拟服务返回的Observable(或直接用this.unitService.getMaxUnit$()) private maxUnit$: Observable<string> = new Observable(observer => { observer.next(MaxUnits.Dollars); // 后续单位变化时,可调用observer.next(newUnitValue)更新 }); ngOnInit(): void { // 订阅Observable并赋值给变量 this.maxUnitSubscription = this.maxUnit$.subscribe(unit => { this.maxUnit = unit; }); } ngOnDestroy(): void { // 组件销毁时取消订阅,避免内存泄漏 this.maxUnitSubscription?.unsubscribe(); } }修改模板使用变量替代函数调用
把模板中的getMaxUnit()替换为定义好的maxUnit变量:<div style="display: flex;"> <table style="width:100%;"> <thead> <tr> <th>Max</th> </tr> </thead> <tbody> <tr *ngFor="let maxValue of maxValueTable"> <td> {{ maxValue | numberFormatter: maxUnit}}</td> </tr> </tbody> </table> </div>
额外优化:使用async管道(无需手动管理订阅)
如果不想手动处理订阅和取消订阅,可以直接在模板中使用async管道,它会自动完成订阅清理:
组件中保留Observable:
maxUnit$: Observable<string> = new Observable(observer => { observer.next(MaxUnits.Dollars); });
模板修改为:
<td> {{ maxValue | numberFormatter: (maxUnit$ | async)}}</td>
内容的提问来源于stack exchange,提问作者Inf Jhoanny
相关产品推荐
相关产品推荐

