【问题标题】:Injection of service in service giving error (Circular dependency injection)在服务提供错误中注入服务(循环依赖注入)
【发布时间】:2018-02-10 07:51:37
【问题描述】:

我已开始在 Angular 5 上构建应用程序,但在将服务注入另一个服务时遇到错误问题。

下面是我的数据服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { environment } from '../../../environments/environment';

import { AuthenticationService } from '../../services/authentication/authentication.service';

@Injectable()
export class DataService {
  private headers;
  public user: any;

  constructor(
    private http: HttpClient,
    private auth: AuthenticationService
  ) {
if (auth.loggedIn) {
      this.setHeader();
    }
  }
}

身份验证服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RouterModule, Router } from '@angular/router';

import { environment } from '../../../environments/environment';
import { error } from 'selenium-webdriver';

import { DataService } from '../../services/dataservice/data.service';

@Injectable()
export class AuthenticationService {
  public loggedIn: boolean;

  constructor(
    private http: HttpClient,
    private dataservice: DataService,
    private router: Router
  ) { }
}

我在这里注入另一个自定义服务,即 AuthenticationService。

但是,在运行时它给了我一个错误,我无法弄清楚它为什么会抛出错误:

Uncaught Error: Can't resolve all parameters for DataService: ([object Object], ?).

已在我的 app.module.ts 中注入提供程序:

providers: [
    DataService,
    AuthenticationService,
    AuthGuard
  ],

提前致谢。

【问题讨论】:

  • 你能发布认证服务吗
  • 现在也发布了认证服务.....
  • 你需要解决循环依赖

标签: angular dependency-injection frontend angular-services


【解决方案1】:

看到您的代码后,您在 DataService 和 AuthenticationService 之间存在循环依赖关系,这在构造函数注入中是不可能的

要解决这个问题,您可以这样做

export class AuthenticationService {
  public token: any;
  dataService: DataService;
  constructor(
    private http: Http,
    injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.dataService= injector.get(DataService));
  } 

【讨论】:

  • 感谢您的回复。我必须在两种服务中都这样做还是只在其中任何一种服务中都这样做?
  • 两者都需要
猜你喜欢
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-26
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多