【问题标题】:call method in ngOnInitngOnInit 中的调用方法
【发布时间】:2019-07-24 07:37:09
【问题描述】:

如果在页面加载时检测到 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'?

【问题讨论】:

  • 请控制台记录您的 cookieValue 变量。有没有价值。
  • 发生了什么?
  • cookie 已设置并显示在检查器中,但不会将 cookieValue 记录到控制台
  • 去掉cookieValue前面的const键盘并检查。
  • 在终端返回这个错误: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'?

标签: angular ngoninit


【解决方案1】:
ngOnInit(): void {
    let cookieValue: string = this.cookieService.get('DarkTheme');
    if (cookieValue === 'True') {
      this.setDarkTheme(true);
      console.log('Dark theme active.')
    }
  }

请添加此代码并再次检查。

【讨论】:

  • 我在终端收到此错误:ERROR in src/app/core/services/theme-switch.service.ts(19,7): error TS2554: Expected 1 arguments, but got 0.
  • 能给我看看 theme-switch.service.ts 文件吗?
  • 这是那个文件。终端错误是 ngOnInit() 中的 this.setDarkTheme()
  • 是的,主题切换工作,如果cookie在那里,它只是没有激活它
  • this.setDarkTheme(true);添加这一行代替 this.setDarkTheme();
猜你喜欢
  • 2020-02-05
  • 2022-01-20
  • 2021-05-29
  • 2019-06-23
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
相关资源
最近更新 更多