的最佳方式我正在使用的应用程序结构如下什么是跨模块共享服务angular2
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);
}
}
我很好奇,想知道是否有任何方式,我可以参考访问HeroService到HeroModule而不是分别从../hero/index
进口Hero
对象和HeroService
其中一个建议是移动hero.service.ts共享包,但我不希望使用这种方法在逻辑上此服务属于英雄包,只有某一部分的它需要在一些其他包中提到。 – Mahesh
导入是一种TypeScript功能,与Angular无关。如果你想在你的代码中使用类作为类型,你必须导入它(带或不带Angular2)。 'NgModule'中的'imports:[]'实现了完全不同的目的,而**是** Angular2特性。 –
一个非常类似的问题后,你应该引导你在正确的方向:http://stackoverflow.com/questions/39621398/angular2-import-components-services-from-module – cmaynard