Search code examples
angularngoninit

call method in ngOnInit


I am trying to call a method if a cookie is detected on page load. If detected, it should load my apps dark theme.

I'm using Angular 7 and 'ngx-cookie-service'.

I can switch themes fine, but cannot figure out how to automatically switch theme when the cookie is detected.

Here is the code for my theme switching service:

import { Injectable, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

// Import Services
import { CookieService } from 'ngx-cookie-service';

@Injectable()
export class ThemeSwitchService implements OnInit {

  constructor( private cookieService: CookieService ) { }

  private _themeDark: Subject<boolean> = new Subject<boolean>();

  isThemeDark = this._themeDark.asObservable();

  ngOnInit(): void {
    const cookieValue: string = this.cookieService.get('DarkTheme');
    if (cookieValue === 'True') {
      setDarkTheme();
      console.log('Dark theme active.')
    }
  }

  setDarkTheme(isThemeDark: boolean) {
    this._themeDark.next(isThemeDark);
    if (isThemeDark) {
      this.cookieService.set('DarkTheme', 'True');
      console.log('Dark theme activated.')
    } else {
      this.cookieService.delete('DarkTheme');
      console.log('Dark theme deactivated.');
    }
  }
}

My hope was to be able to call the theme switching method within ngOnInit, but I can't seem to get it working. This error shows in terminal: ERROR in src/app/core/services/theme-switch.service.ts(20,7): error TS2663: Cannot find name 'setDarkTheme'. Did you mean the instance member 'this.setDarkTheme'?


Solution

  • ngOnInit(): void {
        let cookieValue: string = this.cookieService.get('DarkTheme');
        if (cookieValue === 'True') {
          this.setDarkTheme(true);
          console.log('Dark theme active.')
        }
      }
    

    Please add this code and check again.