Home > OS >  how to pass boolean variable from one service to other service in angular
how to pass boolean variable from one service to other service in angular

Time:11-15

I am trying to pass a boolean value from one service to other service file , in that I am getting boolean value is undefined and I do not find any examples and documents related to it in angular, can anyone guide me to this

need to pass a boolean value from this file:

Auth.service.ts

public Data: boolean;

passValueFunction(){
this.Data =true
}

in this service file, i need to get that boolean value(Data variable in auth.service file) come from auth service file

second.service.ts

constructor(private authService: Authservice){
}

ngOninit(){
console.log(this.authService.Data)
}

in second service file, I am not getting the Data value as true. I want this.authService.Data = true in second service file. I do not have any idea why am getting this.authservice.Data= undefined.

CodePudding user response:

Problem is about that your second.service.ts initiating earlier than function:

passValueFunction(){
  this.Data =true
}

called. Here you can have a few different solutions in case what to you expect from this communication between services. If you need to trigger some function in the second.service.ts only when Data value changed to true I suggest you to create an Observable or BehaviorSubject in the Auth.service.ts and subscribe on the value of this Observable/BS in the second.service.ts.

CodePudding user response:

Here is a sample of how to do it. If you want to get the value from an outside component

In service1.service.ts (or your auth service):

export class Service1Service {

  public data = false;

  constructor() { }

  passValueFunction(){
    this.data =true
  }
}

In service2.service.ts (or your second.service.ts):

export class Service2Service {

  constructor(
    private service1: Service1Service
  ) { }

  getValue() {
    console.log(this.service1.data);
  }
}

In the component using the 2nd service:

    constructor(
    private service2: Service2Service,
    ){
    
  }

  // this method is promted by button
  async onTestAnything() {

    //this.service1.passValueFunction();  // add this method if you 1st want to set the bool using the passValueFunction() method

    this.service2.getValue();
  }

I am only using the 2nd service and the 2nd service is reading the data bool from the 1st service, thus the bool has been passed on

  • Related