/turbo_modules/@angular/[email protected]/bundles/compiler.umd.js 中出现循环依赖错误 (2845:21) 无法解析 BService 的所有参数:(?)

问题描述 投票:0回答:1
A-Service.component.ts

` 从 '@angular/core' 导入 { Injectable, Inject }; 从 './BService' 导入 { BService };

@Injectable({
  providedIn: 'root',
})
export class AService {
  constructor(private bService: BService) {}

  getMessageFromB(): string {
    return this.bService.getMessage();
  }

  getMessage(): string {
    return 'Message from AService';
  }
}
B-service.component.ts
---------------------
import { Injectable, Inject } from '@angular/core';
import { AService } from './AService';

@Injectable({
  providedIn: 'root',
})
export class BService {
  constructor(private aService: AService) {}

  getMessageFromA(): string {
    return this.aService.getMessage();
  }

  getMessage(): string {
    return 'Message from BService';
  }
}
app.component.ts
-------------------
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AService, BService],
})
export class AppComponent {
  messageFromB: string = '';
  messageFromA: string = '';

  constructor(
    private readonly aService: AService,
    private readonly bService: BService
  ) {}

  ngOnInit() {
    this.messageFromB = this.aService.getMessageFromB();
    this.messageFromA = this.bService.getMessageFromA();
  }
}
HTML
------------------
<p>{{ messageFromB }}</p>    
<p>{{ messageFromA }}</p>    `

When I run this I get the below error
---------------------------------------------
Error in /turbo_modules/@angular/[email protected]/bundles/compiler.umd.js (2845:21)
Can't resolve all parameters for BService: (?).

我正在尝试使用 HTML 打印消息,如下所示。我期望 HTML 打印该消息,但由于我的服务具有循环依赖关系,我收到了上述错误

angular angular-services circular-dependency angular11
1个回答
0
投票

正如 Ajeet Shah 已经指出的那样,你有一个循环依赖,这意味着 AService 依赖于 BService,反之亦然,这是没有意义的,会导致循环/循环。

如果您需要某种相互连接,那么我建议引入另一个 CService 来处理“通信”并打破循环。所以 AService -> CService 和 Bservice -> CServiceS

© www.soinside.com 2019 - 2024. All rights reserved.