0

I have defined this service in my Angular Application.

import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class LoginstatusService {
  logBtn: string = '';
  logStat: string = '';
  login: any;

  constructor() {}
  setBtn(data: any) {
    this.logBtn = data;
    console.log(data);
  }

  getBtn(): string {
    return this.logBtn;
  }

  setStatus(data: any) {
    this.logStat = data;
    console.log(data);
  }

  getStatus(): string {
    return this.logStat;
  }

I could set the value to this service from a component and could log the value in the console and check. However, when I try to use the value in the onInit() method of another component, it just returns undefined, instead of the expected value. Could someone explain this behavior, and help me fix this? Thanks in advance.
  • Your code works fine. See this stackblitz. It logs an empty string, as I would expect it to. https://stackblitz.com/edit/angular-ivy-cn92fs – frosty Jun 16 '22 at 05:30
  • @frosty Thanks for your comment. But the thing is, it logs an empty string even after I set a value from a component. – Vikneysh Raj G G A Jun 16 '22 at 05:47
  • Are you perhaps logging `login` which is undefined, since you never assign a value to it? If not, you will need to provide how you are attempting to access the data - "it just returns undefined" what is "it"? – Chris Hamilton Jun 16 '22 at 05:49
  • 2
    where u include service? in @Component decorator or module with each component? Or where both of components are included? (app.module.ts for example) in first case - u create new service each time, if u add service in some global module - service will be shared – Никита Середа Jun 16 '22 at 05:52
  • I believe you should add your service to the list of the component's constructor parameters like constructor( private loginstatusService LoginstatusService){} and resolve all correspondent issue with dependencies – IgorK Jun 16 '22 at 23:46

0 Answers0