angularjs – 是否可以同时在另一个服务中注入服务,反之亦然?

前端之家收集整理的这篇文章主要介绍了angularjs – 是否可以同时在另一个服务中注入服务,反之亦然?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个真实的项目中有一个真实的场景,我需要2个服务来访问彼此的属性和/或方法.我不是Angular专家所以它可能吗?

我试过了,它失败了.这是我的尝试:

app.component.ts

  1. import { Component } from '@angular/core';
  2. import { FirstService } from './first.service';
  3. import { SecondService } from './second.service';
  4.  
  5. @Component({
  6. selector: 'my-app',template: '<h1>Hello world!</h1>',providers: [FirstService,SecondService]
  7. })
  8. export class AppComponent {
  9.  
  10. constructor(public firstService: FirstService,public secondService: SecondService) {
  11. console.log(firstService.foo);
  12. console.log(secondService.bar);
  13. }
  14.  
  15. }

first.service.ts

  1. import { Injectable } from '@angular/core';
  2. import { SecondService } from './second.service';
  3.  
  4. @Injectable()
  5. export class FirstService {
  6.  
  7. foo: string = 'abc';
  8.  
  9. constructor(public secondService: SecondService) {
  10. this.foo = this.foo + this.secondService.bar;
  11. }
  12.  
  13. }

second.service.ts

  1. import { Injectable } from '@angular/core';
  2. import { FirstService } from './first.service';
  3.  
  4. @Injectable()
  5. export class SecondService {
  6.  
  7. bar: string = 'xyz';
  8.  
  9. constructor(public firstService: FirstService) {
  10. this.bar = this.bar + this.firstService.foo;
  11. }
  12.  
  13. }

Plunker:http://plnkr.co/edit/PQ7Uw1WHpvzPRf6yyLFd?p=preview

只是将第二个服务注入第一个服务工作正常,但是一旦我将第一个服务注入第二个服务,它就会失败并向控制台抛出错误.

那有什么不对?

工作解决方案应将以下内容打印到控制台日志:

  1. abcxyz
  2. xyzabc

提前致谢!

AngularJS不允许注入循环依赖.

AngularJS的作者之一MiškoHevery建议找到共同的元素:

  1. +---------+ +---------+
  2. | A |<-----| B |
  3. | | | | +-+ |
  4. | | | +->|C| |
  5. | |------+---->| | |
  6. | | | +-+ |
  7. +---------+ +---------+

并将其提取到第三个服务:

  1. +---------+
  2. +---------+ | B |
  3. | A |<-------------| |
  4. | | | |
  5. | | +---+ | |
  6. | |--->| C |<----| |
  7. | | +---+ +---------+
  8. +---------+

有关更多信息,请参阅MiškoHevery的Circular Dependency in constructors and Dependency Injection.

猜你在找的Angularjs相关文章