只能*ngIf檢查頁面的區域變數還是可以檢查全域變數?
我想做以下事情:
主頁.html
<div *ngIf="debugService.debugActive"></div>
除錯服務.ts
debugActive: boolean = true;
contructor() {}
...
但是現在,我必須先初始化 home.page.ts 上的變數才能在 html 中使用它:
主頁.ts
import { DebugService } from 'src/app/services/debug.service';
localDebugActive: boolean = false;
constructor(
private debugService: DebugService,
) {}
ngOnInit() {
this.localDebugActive = this.debugService.debugActive;
}
主頁.html
<div *ngIf="localDebugActive"></div>
這意味著一個額外的步驟,并用區域變數填充我的整個頁面。是否可以不重新宣告并直接在 HTML 中使用它?
uj5u.com熱心網友回復:
組件訪問服務的唯一方法是注入它,確保依賴注入正常作業。正如您所說,服務并不是真正的全域變數:它們不僅僅是“可從任何地方訪問”。您確實需要使用 DI。
從技術上講,您可以將服務作為public變數而不是變數注入private,并直接從模板訪問其成員。然而,這通常被認為是代碼異味。
uj5u.com熱心網友回復:
有兩種方式:
將服務實體公開
constructor( public debugService: DebugService, ) {}使用方法(推薦方式)。
public isDebugActive() { return this.debugService.debugActive; } <div *ngIf="isDebugActive()"></div>
uj5u.com熱心網友回復:
您可以將注入的服務公開為:
public debugService: DebugService
并在您的模板中使用它。雖然我不太喜歡那樣,但為了簡單的顯示,這會奏效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450290.html
標籤:javascript html 有角度的 离子框架
上一篇:如果選擇,更改所選離子專案的顏色
