"@angular/common": "^5.0.0"
我搜索了很多关于它的内容,大多数人都说是这样做的...我在做什么错了?
我的直觉表明,每次构建(构造)另一个组件时,GlobalService都会很干净,但是我不知道如何正确执行此操作...
GlobalService
import { Injectable } from '@angular/core';
@Injectable()
export class GlobalService{
private currency;
constructor() {
}
setCurrency(val) {
this.currency = val;
}
getCurrency() {
return this.currency;
}
}
GlobalService模块
@NgModule({
...,
providers:[ GlobalService ]
})
设置值(任何组件)
import { GlobalService } from '.path/global.service';
constructor(..., private global: GlobalService) { }
anyMethod(){
this.global.setCurrency('Test Global Service');
console.log(this.global.getCurrency()); // On console => Test Global Service
}
获得价值(另一个组件)
import { GlobalService } from '.path/global.service';
constructor(..., private global: GlobalService) { }
anyMethod(){
console.log(this.global.getCurrency()); // On console => undefined
}