I have uiSettings service, which based on user data will control parts of templates (in different places).
Currently I use this service directly from template. for example:
<li *ngIf="uiService.demoButton()">
<button [routerLink]="/demo" class="secondary">Demo</button>
</li>
In Service:
demoButton():boolean {
return this.demoButtonAvailable;
}
Above property is updated only when something changes for the user (login, logout, update..), but template calls the uiService.demoButton() every second or so.
I believe there is a better way (for performance) to do it. If I use observable, would I observe this value, or wait for event fired after the needed variable is updated?
ngIf condition runs on every change detection, you need to wrap it with some conditional variable. For example
<li *ngIf="demoButtonAvailable">
<button (click)="uiService.demoButton()" class="secondary">Demo</button>
</li>
You can use BehaviorSubject
and async
pipe to notify when something change. You can then use changeDetectionStrategy: ChangeDetection.onPush
or detach changeDetectorRef
and detect changes manually.
You can just simply use the service variable demoButtonAvailable
like below,
...
<li *ngIf="uiService.demoButtonAvailable">
<button [routerLink]="/demo" class="secondary">Demo</button>
</li>
...
If I use observable, would I observe this value, or wait for event fired after the needed variable is updated?
You don't need to use Observable
with event
for a simple Boolean. YES, it will trigger every time because it's method call in the view
( which is not recommended), but you can use service boolean variable unless you want another component variable with service data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.