在Angular中,可以使用服务(service)来实现在组件之间共享变量。下面是一个示例解决方法:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
sharedVariable: string;
constructor() { }
}
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-component1',
template: `
Component 1
Shared Variable: {{ sharedService.sharedVariable }}
`,
})
export class Component1 {
constructor(public sharedService: SharedService) { }
}
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-component2',
template: `
Component 2
Shared Variable: {{ sharedService.sharedVariable }}
`,
})
export class Component2 {
constructor(public sharedService: SharedService) { }
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { Component1 } from './component1.component';
import { Component2 } from './component2.component';
import { SharedService } from './shared.service';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, Component1, Component2],
providers: [SharedService],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,Component1和Component2中都可以使用sharedService.sharedVariable
来共享变量的值。当一个组件修改了共享变量的值,另一个组件也会得到更新。