在服务中注入服务给出错误(循环依赖注入)

时间:2018-02-10 07:51:37

标签: angular dependency-injection frontend angular-services

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

以下是我的dataService

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();
    }
  }
}

的AuthenticationService:

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
  ],

提前致谢。

1 个答案:

答案 0 :(得分: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));
  }