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

angular – 如何避免在bootstrap()函数中声明所有服务?

发布时间:2020-12-17 18:08:53 所属栏目:安全 来源:网络整理
导读:基于我之前的问题: Angular2 “Services” how to @inject one service into another (singletons) 我现在有一个答案,一个新的问题在我身上恍然大悟.这是因为到目前为止我所看到的所有服务都包含在bootstrap方法中. Pascal Precht的博客文章也表明了这一点
基于我之前的问题: Angular2 “Services” how to @inject one service into another (singletons)

我现在有一个答案,一个新的问题在我身上恍然大悟.这是因为到目前为止我所看到的所有服务都包含在bootstrap方法中. Pascal Precht的博客文章也表明了这一点:http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

但对我而言,这与(实际上与Angular1相比)的编码非常难看.为了在这些实例中工作,我必须在app组件中包含我的所有服务(Angular1配置模块).虽然强度应该来自让每个类“模块”负责在整个应用程序中获得自己的单身依赖(提供者).

现在我的问题是:

是否可以让类指定自己的依赖项,而依赖项仍然是所有其他需要相同类的类的单例.就像是:

app.ts

@Component({
  selector: 'app',providers: [
    TeamCollection
  ]
})
@View({
  template: '{{name}}'
})
class TestApp {
  name: string;
  teamCollection: TeamCollection;
  constructor(@Inject(TeamCollection) teamCollection: TeamCollection){
    this.name = 'Angular2';
    this.teamCollection = teamCollection;
  }
}

export function main() {
  bootstrap(TestApp);  
}

team.ts

@Injectable()
export class TeamCollection extends BaseCollection {
    playerCollection: PlayerCollection;
    constructor(playerCollection: PlayerCollection) {
        super();
        this.playerCollection = playerCollection;
    }

    create(data: Object): TeamModel {
        return new TeamModel(data);
    }
}

player.ts

@Injectable()
export class PlayerCollection extends BaseCollection {
    create(data: Object): PlayerModel {
        return new PlayerModel(data);
    }
}

没有我在app组件的providers数组中包含TeamCollection和PlayerCollection.而是在通过App组件提供程序数组创建TeamCollection单例实例时,让Teamcollection将PlayerCollection单例实例注入其构造函数中.

对我来说感觉很不舒服,但如果这是Angular2的方式,我将不得不学会适应它.

编辑:
我想通过说明如果我想要一个由应用程序中的所有组件共享的服务的事实来进一步解释这一点,我必须将它添加到bootstrap方法中.在一个以前可能有50个服务的项目中变得非常难看(如果它必须全部在引导功能中).

另一件事:当你指定像abc /这样的路由时,看到@RouteConfig会查看子类是非常不一致的……意思是组件ABC可以拥有自己的@RouteConfig等.
与我们必须在config()中指定所有内容的Angular1相比,这是一个很大的变化.

EDIT2:
请参阅@alexpods评论:
https://github.com/angular/angular/issues/5063#issuecomment-154753852

@EricMartinez在下面发表评论.
要查看处理angular2模块化的正确方法.

解决方法

您可以将服务导出为单个标记,并在bootstrap()中将它们作为集合提供

a.js

export const MODULE_A: any[] = [Service1,Service2,Service3];

b.js

export const MODULE_B: any[] = [Service3,Service4,Service5];

c.js

import {MODULE_A} from 'a.js';    
import {MODULE_B} from 'b.js';

export const MODULE_C: any[] = [MODULE_A,Module_B,Service6];

main.js

import {MODULE_C} from 'c.js';

bootstrap(AppComponent,[MODULE_C];

这是Angular2中的常见做法,如ROUTER_PROVIDERS,MD_CARD_PROVIDERS,……

(编辑:李大同)

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

    推荐文章
      热点阅读