我正在使用如下所述的应用程序结构
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
from ../hero/index
from Range.io
到目前为止,我们的问题是我们正在不同级别的相同服务中创建两个实例。
DI 树。在树的下部分支中创建的实例是
隐藏在根级别定义的内容。解决方案?避免
在 DI 树的较低级别中创建第二个实例
延迟加载模块,仅使用在以下位置注册的服务实例
树的根。
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';
@NgModule({})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [CounterService]
};
}
}
通过此设置,我们可以将此模块导入到我们的根模块中
AppModule调用forRoot方法注册模块并
服务。
...
import { SharedModule } from './shared/shared.module';
@NgModule({
imports: [
SharedModule.forRoot(),
...
],
...
})
export class AppModule {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)