加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:16:10 所属栏目:安全 来源:网络整理
导读:我在一个真实的项目中有一个真实的场景,我需要2个服务来访问彼此的属性和/或方法.我不是Angular专家所以它可能吗? 我试过了,它失败了.这是我的尝试: app.component.ts import { Component } from '@angular/core';import { FirstService } from './first.s
我在一个真实的项目中有一个真实的场景,我需要2个服务来访问彼此的属性和/或方法.我不是Angular专家所以它可能吗?

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

app.component.ts

import { Component } from '@angular/core';
import { FirstService } from './first.service';
import { SecondService } from './second.service';

@Component({
  selector: 'my-app',template: '<h1>Hello world!</h1>',providers: [FirstService,SecondService]
})
export class AppComponent {

  constructor(public firstService: FirstService,public secondService: SecondService) {
    console.log(firstService.foo);
    console.log(secondService.bar);
  }

}

first.service.ts

import { Injectable } from '@angular/core';
import { SecondService } from './second.service';

@Injectable()
export class FirstService {

  foo: string = 'abc';

  constructor(public secondService: SecondService) {
    this.foo = this.foo + this.secondService.bar;
  }

}

second.service.ts

import { Injectable } from '@angular/core';
import { FirstService } from './first.service';

@Injectable()
export class SecondService {

  bar: string = 'xyz';

  constructor(public firstService: FirstService) {
    this.bar = this.bar + this.firstService.foo;
  }

}

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

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

那有什么不对?

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

abcxyz
xyzabc

提前致谢!

AngularJS不允许注入循环依赖.

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

+---------+      +---------+
|    A    |<-----|  B      |
|         |      |  |  +-+ |
|         |      |  +->|C| |
|         |------+---->| | |
|         |      |     +-+ |
+---------+      +---------+

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

+---------+
+---------+              |    B    |
|    A    |<-------------|         |
|         |              |         |
|         |    +---+     |         |
|         |--->| C |<----|         |
|         |    +---+     +---------+
+---------+

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读