ngOnInit中的调用方法

时间:2019-03-02 12:50:20

标签: angular ngoninit

如果页面加载时检测到cookie,我正在尝试调用一个方法。如果检测到,它将使我的应用程序加载深色主题。

我正在使用Angular 7和'ngx-cookie-service'。

我可以很好地切换主题,但是无法弄清楚在检测到cookie时如何自动切换主题。

这是我的主题切换服务的代码:

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.');
    }
  }
}

我希望能够在ngOnInit中调用主题切换方法,但是我似乎无法使其正常工作。该错误在终端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'?

中显示

1 个答案:

答案 0 :(得分:0)

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

请添加此代码,然后再次检查。