Angular 2 - Exporting Auth Services from AuthModule to AppModule

早过忘川 提交于 2019-12-23 07:40:15

问题


I decided to put LoginComponent, AuthService, LoggedInGuard inside a module called AuthModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthComponent } from './auth.component';
import { LoginComponent } from './components/login/login.component';

import { AuthService } from './services/auth/auth.service';
import { StorageService } from './services/storage/storage.service';
import { RequestService } from './services/request/request.service';

import { LoggedInGuard } from './guards/logged-in.guard';

@NgModule({
  imports: [
    CommonModule
  ],
  providers: [AuthService, LoggedInGuard],
  declarations: [AuthComponent, LoginComponent],
  exports: [AuthService, LoggedInGuard]
})
export class AuthModule { }

And I want to use only AuthService methods in the rest of the Application. And LoggedInGuard to protect non-public routes.

So I tried to import them in AppModule:

import { AuthModule } from './core/auth/auth.module';

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    AuthModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

But in app.routes.ts LoggedInGuard is not available with this line of code:

import { LoggedInGuard } from './core/auth/auth.module'; 

It doesn't compile and it says:

...auth/auth.module has no exported member 'LoggedInGuard'

If I point it to its right place:

import { LoggedInGuard } from './core/auth/guards/logged-in.guard';

It compiles, but is showing the following runtime error:

Unexpected value 'AuthService' exported by the module 'AuthModule'

What do you please suggest me?

Thanks in advance.


回答1:


exports isn't for services. Adding the services to providers is enough. So remove the AuthService and AuthGuard from the exports.

What exports is for is for making components, pipes, directives, and other modules accessible to other modules. So you need to add the AuthComponent, and LoginComponent to that is you want to be able to use them in other modules.

@NgModule({
  imports: [
    CommonModule
  ],
  providers: [AuthService, LoggedInGuard],
  declarations: [AuthComponent, LoginComponent],
  exports: [AuthComponent, LoginComponent]
})
export class AuthModule { }

Also note that importing the AuthModule to the AppModule, only makes the components available to other components declared in the AppModule. Any other modules that want to use these components should import the AuthModule.



来源:https://stackoverflow.com/questions/40498543/angular-2-exporting-auth-services-from-authmodule-to-appmodule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!