Ionic *ngIf - 检查全局变量

Ionic *ngIf - Check for global variables

可以*ngIf只检查页面的局部变量还是可以检查全局变量?

我想做以下事情:

home.page.html

<div *ngIf="debugService.debugActive"></div>

debug.service.ts

debugActive: boolean = true;

contructor() {}
...

但是现在,我必须先在 home.page.ts 上初始化变量,以便在 html:

中使用它

home.page.ts

import { DebugService } from 'src/app/services/debug.service';

localDebugActive: boolean = false;

constructor(
    private debugService: DebugService,
) {}

ngOnInit() {
    this.localDebugActive = this.debugService.debugActive;
}

home.page.html

<div *ngIf="localDebugActive"></div>

这意味着一个额外的步骤,用局部变量填充我的整个页面。是否可以不重新声明并直接在 HTML?

中使用它?

您可以将注入的服务公开为 public :

public debugService: DebugService

并在您的模板中使用它。 虽然我不太喜欢那样,但是为了简单的显示,这样就可以了。

组件访问服务的唯一方法是注入它,确保依赖注入正常工作。正如您所说,服务并不是真正的全局变量:它们不仅仅是“可从任何地方访问”。您确实需要使用 DI。

技术上 您可以将服务作为 public 变量而不是 private 变量注入,并直接从模板访问其成员。然而,这通常被认为是代码异味。

有两种方式:

  1. 创建服务实例public

    constructor(
        public debugService: DebugService,
    ) {}
    
  2. 使用方法(推荐方式)。

    public isDebugActive() {
        return this.debugService.debugActive;
    }
    
    <div *ngIf="isDebugActive()"></div>