在Angular中,可以使用服务(Service)来共享数据和状态,而不是直接将值设置给公共变量。以下是一个示例解决方法:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
public sharedValue: any;
constructor() { }
}
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
constructor(private dataService: DataService) { }
setValue(value: any) {
this.dataService.sharedValue = value;
}
}
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';
@Component({
selector: 'app-another-example',
templateUrl: './another-example.component.html',
styleUrls: ['./another-example.component.css']
})
export class AnotherExampleComponent {
sharedValue: any;
constructor(private dataService: DataService) { }
getValue() {
this.sharedValue = this.dataService.sharedValue;
}
}
通过使用服务来共享数据,可以避免直接设置公共变量的问题,并且可以在整个应用程序中共享数据和状态。
下一篇:Angular无法加载其他路由