【问题标题】:Cannot read property of undefined in APP_INITIALIZER - Angular无法读取 APP_INITIALIZER 中未定义的属性 - Angular
【发布时间】:2019-06-20 05:51:57
【问题描述】:

我正在尝试使用 APP_INITIALIZER 执行我的 saveURL 方法,但我的 saveURL 方法出现错误。

ERROR TypeError: Cannot read property 'setCookie' of undefined

App.modulte.ts

 ...
   export function saveUrl(dualLogonService: DualLogonService) {
     console.debug('Executing saveUrl');
      return (): Promise<any> => {
        dualLogonService.setCookie(); //THIS IS WHAT GIVES ME ERROR
        return null;
      };
    }
   ...
    providers: [
    ...
          {
              provide: APP_INITIALIZER,
              useFactory: saveUrl,
              deps: [DualLogonService],
              multi: true
          }
    ]

DualLogonService.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthenticationService } from '@sec/security';
import { appConfigMapping } from 'src/environments/app.config.mapping';
import { of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DualLogonService implements CanActivate {
...
  constructor(
    private router: Router,
    private authService: AuthenticationService
  ) {}
..

  setCookie(): void {
    document.cookie = 'Deeplink' + '=' + this.router.url + ';path=/';
  }

【问题讨论】:

    标签: angular


    【解决方案1】:

    将 DualLogonService 添加到 Providers-array

    【讨论】:

    • 我之前试过了,我得到了这个错误:Uncaught Error: Provider parse errors: Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR -&gt;]"): in NgModule
    • 显然您正在注入具有依赖关系(http 或其他服务相同)的其他服务(未在您发布的代码中显示)。尝试按照一些教程来了解它是如何工作的,例如:intertech.com/Blog/…
    • 我用更多代码更新了我的问题。所以我的理解是我必须将我在构造函数中注入的其他服务添加到 app.module.ts 中的提供程序?
    • 我会抽象出从 duallogonservice 到 InitAppService 的所有内容,该服务中只有 setcookie 方法,你应该很高兴!
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2016-01-12
    • 2015-09-08
    • 2016-05-12
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多