Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Exporting Auth Services from AuthModule to AppModule

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.

like image 536
Pasp Ruby Avatar asked Nov 09 '16 00:11

Pasp Ruby


1 Answers

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.

like image 164
Paul Samsotha Avatar answered Nov 11 '22 18:11

Paul Samsotha