How to avoid Global Variable in Angular service

Viewed 28

I have a use case where i have a service file and in that service file i have a global Variable 'check'. The value of check is getting updated by some function in this service. I have to use this check variable in a component and as its global i can easily use this.

But i don't want to make this variable Global in service, is there any alternative approach to achieve the same without making this global.

test.service.ts

export class TestService extends AbstractGridServiceHandler {
check = '';
updateVal(){
   this.check = 'updated';
}
}

test1.component.ts

import { TestService } from 'service';
export class testComponent{
constructor(private ts: TestService) {
super();
}
  ngOnInit() {
      let a = this.ts.check ;
    
  }
}
1 Answers

you can make the variable accessible as a getter:

export class TestService extends AbstractGridServiceHandler {

  private _check = '';

  get check():string{
    return this._check;
  }

  updateVal(){
    this._check = 'updated';
  }
}
Related