javascript - 应用程序范围内可访问和可变的变量

标签 javascript html angular typescript

我有一个导航栏,用于检查打开/关闭变量是真还是假,我将其称为“navcontrol”。 我的导航栏有一个组件,每个页面都有一个不同的组件。

我的 app.component.html :

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

问题是,一个按钮改变了 navcontrol,这个按钮在 "app-navbar" 上。每个页面也需要根据navcontrol的值改变padding,它们移动到底部。

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

在 Angular 文档上,我看到我可以ng generate service navbarcontrol 然后像这样使用:

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


@Injectable({
  providedIn: 'root',
})

export class NavbarcontrolService {

  static navcontrol: boolean;
  constructor()
  {
      console.log(NavbarcontrolService.navcontrol)
  }
}

然后是我的 navbar.component.ts 和 page1.component.ts :

export class NavbarComponent implements OnInit {

  navcontrol = NavbarcontrolService.navcontrol;

然后在我的 page1 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;
}

关于javascript - 应用程序范围内可访问和可变的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295275/

相关文章:

javascript - 在 Canvas 上画线,但最后的线褪色了

javascript - 将数据从服务推送到组件的最佳方式是什么?

javascript - 通过单击内部的链接在两个 <div> 标签之间切换

html - 将框架放在 Bootstrap 轮播周围

node.js - Angular - 将 Json 对象传递给显示 [Object Object] 的子对象

javascript - 将文本文件读取到数组

html - 如何在文本上应用 CSS 渐变,从透明颜色到不透明颜色

javascript - 如何使用此脚本创建多个插入文本区域的按钮

javascript - 导入 OAS 生成的 api 时 angular 8 崩溃

angular - 无法从 Dialog Flow 访问客户端访问 token ,我需要在 Angular 应用程序中使用