0

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'?

lckdwn
  • 45
  • 1
  • 9
  • Please console log your cookieValue variable. it has value or not. – shubham chhapre Mar 02 '19 at 12:54
  • What happened ? – shubham chhapre Mar 02 '19 at 12:56
  • The cookie is set and shows up in the inspector, but it won't log the cookieValue to console – lckdwn Mar 02 '19 at 12:58
  • remove const keyboard in front of cookieValue and check. – shubham chhapre Mar 02 '19 at 12:59
  • It returns this error in terminal: `ERROR in src/app/core/services/theme-switch.service.ts(17,18): error TS2693: 'string' only refers to a type, but is being used as a value here. src/app/core/services/theme-switch.service.ts(18,9): error TS2304: Cannot find name 'cookieValue'. src/app/core/services/theme-switch.service.ts(19,19): error TS2304: Cannot find name 'cookieValue'. src/app/core/services/theme-switch.service.ts(20,7): error TS2663: Cannot find name 'setDarkTheme'. Did you mean the instance member 'this.setDarkTheme'?` – lckdwn Mar 02 '19 at 13:01
  • i have added answer please apply it and let me know. – shubham chhapre Mar 02 '19 at 13:04

1 Answers1

0
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.

shubham chhapre
  • 296
  • 1
  • 14