要从另一个组件中更改变量,你可以使用Angular中的服务(service)来共享数据。
首先,创建一个名为data.service.ts的新服务文件,并在其中定义一个变量和两个方法。
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
private myVariable: string;
constructor() {
this.myVariable = 'Initial value';
}
getVariable(): string {
return this.myVariable;
}
setVariable(newValue: string): void {
this.myVariable = newValue;
}
}
接下来,在要更改变量的组件中,将DataService注入到构造函数中,并使用它来获取和设置变量的值。
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component1',
template: `
Variable value: {{ variable }}
`,
})
export class Component1 {
variable: string;
constructor(private dataService: DataService) {
this.variable = dataService.getVariable();
}
changeVariable(): void {
this.dataService.setVariable('New value');
this.variable = this.dataService.getVariable();
}
}
最后,在另一个组件中,也将DataService注入到构造函数中,并使用它来获取变量的值。
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component2',
template: `
Variable value: {{ variable }}
`,
})
export class Component2 {
variable: string;
constructor(private dataService: DataService) {
this.variable = dataService.getVariable();
}
}
现在,当在Component1组件中点击按钮更改变量的值时,Component2组件中显示的变量值也会更新。这是因为它们使用了同一个DataService实例来共享数据。