应用范围可访问和可变变量



我有一个导航栏,可以检查变量是真还是假以打开/关闭,我称之为"导航控制"。我的导航栏有一个组件,每个页面都有一个不同的组件。

我的应用程序组件.html :

<app-navbar></app-navbar>
<router-outlet></router-outlet>

问题是,一个按钮更改导航控件,此按钮位于"应用程序导航栏">上。每个页面还需要根据 navcontrol 的值更改填充,它们移动到底部。

所以我在每个页面上都有一个侦听器[class.opened]="navcontrol === true",添加一个使用 css 填充的打开类。

在一个角度文档中,我看到我可以ng generate service navbarcontrol然后像这样使用:

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class NavbarcontrolService {
static navcontrol: boolean;
constructor()
{
console.log(NavbarcontrolService.navcontrol)
}
}

然后我的导航栏.component.ts和page1.component.ts:

export class NavbarComponent implements OnInit {
navcontrol = NavbarcontrolService.navcontrol;

然后在我的页面上1 html:

<div class="content " [class.toggled]="navcontrol=== true">

我的导航栏 html,其中更改导航控件的按钮是:

<button type="button" class="button"
[class.isopen]="navcontrol=== true"
[class.isclosed]="navcontrol=== false"
(click)="navcontrol= !navcontrol">
</button>

当我单击"app-navbar">内的按钮时,它会标记本地 navcontrol 变量,来自"app-page1">的文本没有收到更改,因此它们引用的是不同的变量,而不是单个全局变量。 我如何声明一个全局">navcontrol",如果我在我的"app-navbar"上更改它,我的"app-page1">也将检查相同的变量并看到它已经更改?

您可以在组件中使用属性 getter 和 setter 访问全局变量。此技术将确保对navcontrol属性的所有调用最终都将引用相同的全局变量。

export class MyComponent {
constructor(private navbarcontrolService: NavbarcontrolService) { }
get navcontrol(): boolean {
return this.navbarcontrolService.navcontrol;
}
set navcontrol(value: boolean) {
this.navbarcontrolService.navcontrol = value;
}
...
}

与服务:

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class NavbarcontrolService {
navcontrol: boolean;
}

最新更新