我正在尝试使用Angular 6创建全局变量文件。此文件中的变量可由其他组件更改。因此,我看到了this示例,并试图在我的项目中实现它。
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Globals } from './globals';
import { AppComponent } from './app.component';
import { SideMenuComponent } from './side-menu/side-menu.component';
@NgModule({
declarations: [
AppComponent,
SideMenuComponent
],
imports: [
BrowserModule,
],
providers: [ Globals ],
bootstrap: [AppComponent]
})
export class AppModule { }
side-menu.component.ts:
import { Component, OnInit } from '@angular/core';
import { sideMenu } from './side-menu.links.js';
import { Globals } from '../globals.js';
@Component({
selector: 'side-menu',
templateUrl: './side-menu.component.html',
styleUrls: ['./side-menu.component.css']
})
export class SideMenuComponent implements OnInit {
isSideMenuOpen: boolean;
mainLinks: {url: string, target: string}[]}[] = []
bottomNav: {url: string, target: string}[]}[] = []
constructor(private globals: Globals) {
this.isSideMenuOpen = globals.isSideMenuOpen;
}
ngOnInit() {
this.mainLinks = sideMenu.mainLinks;
}
toggleSideMenu() {
this.globals.isSideMenuOpen = !this.isSideMenuOpen;
}
}
globals.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class Globals {
isSideMenuOpen: boolean = true;
}
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ConfigUi</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body [class.sidemenu-open]="globals.isSideMenuOpen">
<app-root class="grafana-app"></app-root>
</body>
</html>
isSideMenuOpen
布尔值用于在正文中添加或删除类。使用toggleSideMenu()
按钮可通过侧面菜单组件内的功能切换此变量。
错误:
StaticInjectorError(AppModule)[SideMenuComponent -> Globals]:
StaticInjectorError(Platform: core)[SideMenuComponent -> Globals]:
NullInjectorError: No provider for Globals!
为什么这不起作用?我该如何运作?
答案 0 :(得分:1)
我正在使用相同的example
如果您在app.module.ts中将Globals作为提供者添加,则应该可以。
我所做的是:
全局变量:
import { Injectable } from '@angular/core';
@Injectable()
export class Globals {
section: string = 'Value';
changeValue(value: string){
this.section = value;
}
}
在组件上:
import { Globals } from '../globals';
export ClassName implement OnInit {
g: Globals;
constructor(public globals: Globals){
this.g = globals;
}
}
然后在html处修改值:
<div (click)="g.changeValue('StringValue')"> <div>