[英]Injection of service in service giving error (Circular dependency injection)
I have started building an application on Angular 5 butI am facing an error issue when injecting a service in another service.我已开始在 Angular 5 上构建应用程序,但在将服务注入另一个服务时遇到错误问题。
Below is my 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
) { }
}
Here I am injecting another custom service, ie, AuthenticationService.在这里,我正在注入另一个自定义服务,即 AuthenticationService。
However, while running it gives me an error and I am not able to figure out why its throwing error:但是,在运行时它给了我一个错误,我无法弄清楚它抛出错误的原因:
Uncaught Error: Can't resolve all parameters for DataService: ([object Object], ?).
Have injected in the provider in my app.module.ts:在我的 app.module.ts 中注入了提供者:
providers: [
DataService,
AuthenticationService,
AuthGuard
],
Thanks in advance.提前致谢。
After seeing your code You have a circular dependency between DataService and AuthenticationService which is not possible with constructor injection看到您的代码后,您在 DataService 和 AuthenticationService 之间存在循环依赖,这是构造函数注入不可能实现的
To fix this, you can do要解决这个问题,你可以这样做
export class AuthenticationService {
public token: any;
dataService: DataService;
constructor(
private http: Http,
injector:Injector;
private router: Router
) {
setTimeout(() => this.dataService= injector.get(DataService));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.