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 ?
CodePudding user response:
Your method expects 2 arguments but you are calling it with 0, try to remove the arguments of the function and call it at your constructor or pass the expected arguments for it.
Print any value at the service function that you are calling to check if it is reaching that function correctly.
CodePudding user response:
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
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());
}
}