AngularService的共享数据为何在HTML中未被更新?
创始人
2024-10-29 09:30:22
0

这通常是由于变化检测策略引起的。默认情况下,Angular采用的是Zone.js库中的ChangeDetectionStrategy.Default策略,每次数据绑定时都会重新检查组件中所有绑定的属性。这可能会导致性能问题,因此在某些情况下需要更改检测策略。

一种解决方法是将数据绑定到Observable或Subject,并使用AsyncPipe在HTML中进行订阅。在这种情况下,数据的推送将在异步上下文中触发更新。

例如:

// service.ts import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class DataService { private _dataSubject = new Subject(); data$ = this._dataSubject.asObservable();

updateData(newValue: number): void { this._dataSubject.next(newValue); } }

// component.ts import { Component } from '@angular/core'; import { DataService } from './data.service';

@Component({ selector: 'app-example', template: '

{{ value$ | async }}
' }) export class ExampleComponent { value$ = this.dataService.data$;

constructor(private dataService: DataService) {}

handleChange(newValue: number): void { this.dataService.updateData(newValue); } }

在上面的示例中,我们使用一个名为_dataSubject的Subject来存储数据,并将其公开为名为data$的Observable。在组件中,我们通过订阅value$来接收数据的更新,并在updateData方法中使用next方法来推送新数据。

请注意,每当数据更新时都会触发Angular的变化检测机制,这使得我们可以在HTML中看到新的值。

如果您不想使用Observable或Subject,可以考虑使用ChangeDetectionStrategy.OnPush策略。在这种情况下,只有当输入属性引用更改时(即,指针由一个对象指向另一个对象),才会触发变化检测。这可以提高性能并减少不必要的检测。

例如:

// component.ts import { Component, ChangeDetectionStrategy } from '@angular/core'; import { DataService } from './data.service';

@Component({ selector: 'app-example', template: '

{{ dataValue }}
', changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleComponent { dataValue: number;

constructor(private dataService: DataService) {}

ngOnInit() { this.dataService.data$.subscribe(newValue => { this.dataValue = newValue; }); }

handleChange(newValue: number): void { this.dataService.updateData(newValue); } }

在上面的示例中,我们在示例组件的元数据中添加了一个名为ChangeDetectionStrategy.OnPush的属性,告

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...