简体   繁体   English

我如何从另一个模块导入服务

[英]How can i import a service from another module

In my application, I have different modules. 在我的应用程序中,我有不同的模块。 I want them to have one common navigation service. 我希望他们拥有一项通用的导航服务。 But when I call a service in a component of module I get an error. 但是,当我在模块的组件中调用服务时,会出现错误。

Can't resolve all parameters for PersonalPage: (?).

What could be the problem? 可能是什么问题呢?

app.module.ts app.module.ts

import { NavService } from "../shared/nav-service/nav.service";
import { PersonalPageModule } from '../pages/personal/personal.module';

@NgModule({
     ...
     imports: [
         ...
         PersonalPageModule,
         ...
     ],
     providers: [
         ...
         NavService,
         ...
     ]
     ...
});

personal.ts personal.ts

import { NavService } from "../../shared/nav-service/nav.service";

@IonicPage({
  name: 'page-personal',
  segment: 'personal/:hash' 
})

@Component({
  selector: 'page-personal',
  templateUrl: 'personal.html' 
})

export class PersonalPage implements OnDestroy{
  constructor(private navService: NavService) {
  }
}

nav.service.ts nav.service.ts

import { Injectable } from '@angular/core';
import { PersonalPage } from '../../pages/personal/personal';

@Injectable()
export class NavService {}

a service is disponible to all the components that was in a module defined in the module where the service is 服务对服务所在的模块中定义的模块中的所有组件负责

@NgModule({
    declarations: [
        AppComponent,  //<--this can access to the service
        MyHeaderComponent    ],  //<--this one too
    imports: [
        ...
        Module2Module,  //<--all the components defined in this module too
        Module3Module,   //<--all the components defined in this module too
        AppRoutingModule,
        DndModule.forRoot()
    ],
    providers: [MyService]
})

if Module2Module import Submodule3, all the component defined in Submodule 3 too. 如果Module2Module导入Submodule3,那么所有在Submodule 3中定义的组件也是如此。 And Module2Module or Module3Module NOT include the service. 并且Module2Module或Module3Module不包含服务。 That's the service are declared as provider in a unique module 那就是服务被声明为唯一模块中的提供者

You service needn't import any module or component what want to be use it, is the component that want to use the service who must import then and use in the constructor 您的服务不需要导入任何要使用的模块或组件,而是要使用该服务的组件,则必须先导入并在构造函数中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM