Search code examples
javascriptangulartypescriptservicecomponents

wrong result when I pass a value from a service to my angular component


I created an Angular service that contains a simple string variable, then in this service I update it's value in a function. Then I call this function in my component.ts (by dependency injection), I got the initial value of my variable (the targed is to get the updated value)

this is the service :

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpService } from '../http/http.service';

@Injectable({
   providedIn: 'root',
})
export class MyService {
constructor() {}

callLogsToggle = 'on';

this is the function created in this service

public setHubspotTogglesStatus() {
 this.callLogsToggle = 'off'; //updated to off
}

this my component.ts

import { ActivatedRoute, Router } from '@angular/router';

@Component({
selector: 'my-selector',
templateUrl: './myCompo.component.html',
styleUrls: ['./myCompo.component.sass'],
})
export class MyComponent implements OnInit {

constructor(
    private mySevice: MyService,
    
) {
   this.myService.setHubspotTogglesStatus()
   console.log(this.mySevice.callLogsToggle) //The result is "on" 
                                            //The variable is not 
                                            //updated
    
}

So any help to resolve this small issue ?


Solution

  • In your service file

    import { Injectable } from '@angular/core';
    import { environment } from '../../../environments/environment';
    import { HttpService } from '../http/http.service';
    
    @Injectable({
       providedIn: 'root',
    })
    export class MyService {
      callLogsToggle:string;
      constructor() {
       this.callLogsToggle = 'on';
      }
    
      public setHubspotTogglesStatus() {
        this.callLogsToggle = 'off'; //updated to off
      }
    
      public getcallLogsToggle():string {
        return this.service.callLogsToggle;
      }
    }
    

    In your component.ts file

    import { ActivatedRoute, Router } from '@angular/router';
    
    @Component({
    selector: 'my-selector',
    templateUrl: './myCompo.component.html',
    styleUrls: ['./myCompo.component.sass'],
    })
    export class MyComponent implements OnInit {
    
    constructor( private mySevice: MyService) {}
    
    ngOnInit(): void {
       this.myService.setHubspotTogglesStatus();
       console.log(this.mySevice.getcallLogsToggle());
     }
    
    }