在Angular 7中,如果你遇到了更新全局变量时的问题,可以尝试以下解决方法:
例如,创建一个名为GlobalService的新服务:
import { Injectable } from '@angular/core';
@Injectable()
export class GlobalService {
globalVariable: string = 'initial value';
updateGlobalVariable(newValue: string) {
this.globalVariable = newValue;
}
}
在需要访问或更新全局变量的组件中,注入GlobalService并使用它:
import { Component } from '@angular/core';
import { GlobalService } from './global.service';
@Component({
selector: 'app-my-component',
template: `
{{ globalService.globalVariable }}
`
})
export class MyComponent {
constructor(private globalService: GlobalService) {}
updateGlobalVariable() {
this.globalService.updateGlobalVariable('new value');
}
}
在一个全局变量的服务中,创建一个Subject或BehaviorSubject:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class GlobalService {
globalVariable: Subject = new Subject();
updateGlobalVariable(newValue: string) {
this.globalVariable.next(newValue);
}
}
在需要访问或更新全局变量的组件中,订阅该Subject:
import { Component, OnInit } from '@angular/core';
import { GlobalService } from './global.service';
@Component({
selector: 'app-my-component',
template: `
{{ globalVariable }}
`
})
export class MyComponent implements OnInit {
globalVariable: string;
constructor(private globalService: GlobalService) {}
ngOnInit() {
this.globalService.globalVariable.subscribe(value => {
this.globalVariable = value;
});
}
updateGlobalVariable() {
this.globalService.updateGlobalVariable('new value');
}
}
这些方法可以帮助你在Angular 7中成功更新全局变量。根据你的需求和项目的规模,选择适合你的方法。