Nirodha Wickramarathna
Nirodha Wickramarathna

Reputation: 291

How to change angular service variable value?

This is my angular service.ts code. How I change this 'loginstatus' variable value to 'true' in login() method of app.componenent.ts

import { Injectable } from '@angular/core';
    
 var loginstatus:false;
    
    @Injectable({
      providedIn: 'root'
    })
    export class CurdService {
    
      constructor() { }
     
    }

Upvotes: 0

Views: 2302

Answers (2)

Santhosh John
Santhosh John

Reputation: 728

You declared loginstatus as a var which can't be accessed outside the service file. Just remove the var and declare the variable inside your service class file.

Please Note: Though this may work, I recommend using the variables inside the component and not in the services as it is not the responsibility of a Service class, but a Component class. Still, you need it in services, consider using Subject() or BehaviorSubject() as services are used in multiple places (worth considering that Subjects will lose values when the page is refreshed and mechanisms to tackle that needs to be in-place)!

Upvotes: 1

Pilpo
Pilpo

Reputation: 1276

Your variable loginstatus is outside the scope of your service. Modify it this way

@Injectable({
  providedIn: 'root'
})
export class CurdService {
  loginstatus = false
  constructor() { }
 
}

And then, in your app.component inject your service:

constructor(curdService: CurdService) {
   this.curdService.loginstatus = true;
}

Upvotes: 4

Related Questions