Angular 2 - 从组件访问变量到类的外侧(没有父级,子级关系)

Sp *_*aju 3 angular

我正在尝试从组件访问变量到类外部,并且没有与该组件的关系(父/子).我做了一些研发工作,但找不到办法.如果有任何想法请帮助我.

例如,组件类似于:BankAccountComponent.ts

@Component({
  selector: 'app-bank-account',
  templateUrl: './app-bank.component.html',
  styleUrls: ['./app-bank.component.scss']
export class BankAccountComponent {
  accountFlag: false;
  changeFlag(){
    this.accountFlag = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

侧面课程如:CustomValidator.ts

export class CustomValidators extends Validators { 
static bankAccValidator(control: AbstractControl): { [key: string]: boolean } | null {
//Here I need to use that component variable i.e accountFlag
return null;
}
Run Code Online (Sandbox Code Playgroud)

Aks*_*put 5

服务设计相同,(依赖注入)

@Injectable()
export class SomeService {
//define a variable
someVariable = "xyz";
}
Run Code Online (Sandbox Code Playgroud)

在父模块或组件的根模块中提供此服务(app.module.ts)

在组件中注入服务

one.component.ts
constructor(private someService: SomeService) {

}
// update the variable here
this.someService.someVariable = "Value Changed"

two.component.ts
constructor(private someService: SomeService) {}
// updated variable can be accessed here
console.log(this.someService.someVariable);
Run Code Online (Sandbox Code Playgroud)