gpt4 book ai didi

angular - 在 angular2 中跨模块共享服务的最佳方式是什么

转载 作者:太空狗 更新时间:2023-10-29 17:22:12 25 4
gpt4 key购买 nike

我正在使用下面提到的应用程序结构

index.ts
|-app.module.ts
|-app.component.ts
|--hero (directory)
|-hero.module.ts
|-hero.ts (Data Object)
|-hero.service.ts
|-hero.component.ts
|-index.ts (this file exports data obj, service, component & module)
|--dashboard (directory)
|-dashboard.module.ts
|-dashboard.component.ts
|-index.ts (this file exports module and component)

我希望在仪表板组件中使用英雄服务。下面是我现在正在使用的代码片段,它按预期工作。但不确定这是否是一种好的做法。

import { Component, OnInit } from '@angular/core';

import { Hero, HeroService } from '../hero/index';
import {Router} from '@angular/router';

@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: ['dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];

constructor(private heroService: HeroService, private router: Router) { }

ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
}

gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}

我很想知道是否有任何方法可以通过引用 HeroModule 来访问 HeroService 而不是分别从 导入 Hero 对象和 HeroService ../英雄/索引

最佳答案

来自 Range.io

So far our problem is that we are creating two instances of the same services in different levels of the DI tree. The instance created in the lower branch of the tree is shadowing the one defined at the root level. The solution? To avoid creating a second instance in a lower level of the DI tree for the lazy loaded module and only use the service instance registered at the root of the tree.

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';

@NgModule({})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [CounterService]
};
}
}

With this setup, we can import this module in our root module AppModule calling the forRoot method to register the module and the service.

...
import { SharedModule } from './shared/shared.module';

@NgModule({
imports: [
SharedModule.forRoot(),
...
],
...
})
export class AppModule {}

关于angular - 在 angular2 中跨模块共享服务的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com