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的属性,告

相关内容

热门资讯

课程透视!德州局怎么透视,po... 课程透视!德州局怎么透视,pokemmo免费脚本,总结教程(有挂教程)-哔哩哔哩1、下载安装好德州局...
操作透视!hhpoker免费透... hhpoker免费透视脚本是一款专注玩家量身打造的游戏记牌类型软件,在hhpoker免费透视脚本这款...
资料透视!werplan免费挂... 您好:werplan免费挂下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
绝活透视!德普之星怎么设置埋牌... 绝活透视!德普之星怎么设置埋牌,wepoker透视版下载,安装教程(有挂秘籍)-哔哩哔哩 【无需打开...
方式透视!wpk辅助,wepo... 方式透视!wpk辅助,wepoker怎么挂底牌,靠谱教程(有挂神器)-哔哩哔哩;亲,wepoker怎...
窍门透视!wepoker私人局... 窍门透视!wepoker私人局辅助器怎么用,红龙poker辅助指令,玩家教你(有挂秘笈)-哔哩哔哩 ...
项目透视!wepoker永久免... 大家好,今天小编来为大家解答wepoker永久免费脚本这个问题咨询软件客服可以免费测试直接加微信(1...
机巧透视!aapoker辅助插... 机巧透视!aapoker辅助插件工具,We poker辅助器下载,攻略教程(有挂神器)-哔哩哔哩 >...
模板透视!pokemmo手机版... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
绝活透视!wpk软件是真的吗,... 绝活透视!wpk软件是真的吗,wepoker私人局俱乐部辅助,透牌教程(确实有挂)-哔哩哔哩;亲,w...