本文介绍了在angular2中跨模块共享服务的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用如下所述的应用程序结构
I am using an application structure as mentioned below
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)
我希望在仪表板组件中使用英雄服务.下面是我现在正在使用的代码片段,它按预期工作.但是不确定这是否是一个好习惯.
I wish to use hero service in dashboard component.Below is the code snippet I am using right now and its working as expected. But not sure if its a good practice.
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/index
I am curious to know if there is any way that I can access HeroService with reference to HeroModule rather than separately importing Hero
object and HeroService
from ../hero/index
推荐答案
来自 Range.io
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CounterService } from './counter.service';
@NgModule({})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [CounterService]
};
}
}
...
import { SharedModule } from './shared/shared.module';
@NgModule({
imports: [
SharedModule.forRoot(),
...
],
...
})
export class AppModule {}
这篇关于在angular2中跨模块共享服务的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!