将模块导入另一个模块以访问服务

时间:2017-04-24 02:30:26

标签: angular import

我有以下module

import { NgModule } from '@angular/core';
import { ActivitiesService } from '../services/activities.service';

@NgModule({
    declarations: [],
    imports: [ActivitiesService],
    providers: [],
    bootstrap: [],
    exports: [ActivitiesService]
})

export class ActivitiesModule { }

ActivitiesService将通过我的应用程序中的不同组件使用,因此我决定为ActivitiesService创建一个共享模块,该模块导入服务并将其导出,使其可供其他模块导入。

然后我创建了一个新的module,此模块将导入上面的module,如下所示:

import { NgModule } from '@angular/core';

// Components
import { ProfileComponent } from '../component/profile/profile.component';

// Routing
import { profileRouting } from '../routing/profile-routing';

// Shared << IMPORTED OTHER MODULE HERE
import { ActivitiesModule } from '../../shared/modules/activities.module';


import { FormsModule, ReactiveFormsModule } from '@angular/forms';

// Authentication Guard
import { AuthenticationGuard } from '../../shared/guards/authentication.guard';


@NgModule({
    imports: [
        profileRouting,
        FormsModule, 
        ReactiveFormsModule,
        ActivitiesModule],
    declarations: [
        ProfileComponent],
    providers: [AuthenticationGuard]
})

export class ProfileModule { }

现在我的ProfileComponent内有以下声明:

// Services
import { ActivitiesService } from '../../../shared/services/activities.service';

ProfileComponent

的构造函数
constructor(private activityService: ActivitiesService) {}

我的ngOnInit方法如下:

ngOnInit() {

   this.activityService.getActivities();

}

然而,当我运行它并导航到Profile页面时,我收到错误消息:

  

错误:未捕获(在承诺中):错误:意外值   &#39; ActivitiesService&#39;由模块&#39; ActivitiesModule&#39;导入。请   添加@NgModule注释。错误:意外的值   &#39; ActivitiesService&#39;由模块&#39; ActivitiesModule&#39;导入。请   添加@NgModule注释。

我检查了命名约定,检查了@NgModule注释并且它都是正确的。有人能否解释我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

通过执行以下操作解决:

ActivitiesModule

import { NgModule } from '@angular/core';
import { ActivitiesService } from '../services/activities.service';

@NgModule({
    declarations: [],
    imports: [],
    providers: [ActivitiesService],
    bootstrap: [],
    exports: []
})

export class ActivitiesModule { }

导入ProfileModule保持不变。