如何再次使Angular2 Service Singleton ....

时间:2017-03-22 01:24:34

标签: angular singleton angular2-routing angular2-services angular2-guards

请允许我再次询问有关如何在angular2中制作单件服务的问题。我正在尝试使用注入的身份验证服务来实现身份验证服务。

但是,每当我访问由auth guard保护的路由时,始终会调用注入服务的构造函数。即“console.log(”authgaurd created“)”和“console.log”(“auth services created”);“在下面的代码段中,每次都会调用而不是一次。

我遵循了类似问题中提出的指南,包括:How to make Angular2 Service singleton?

但看起来我可能会遗漏某些东西......帮助?

使用@ angular / core“:”^ 2.3.1

//app.module.ts

import {AuthService} from "./auth.service";
import { AuthGuard } from './auth-guard.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [ 
    QAModule,
    AppRoutingModule,
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

服务

//auth.service

@Injectable()
export class AuthService {

    constructor() {

        console.log("auth services created");
    }
}


//auth-guard.service

@Injectable()
export class AuthGuard implements CanActivate {

    constructor( authService: AuthService) {

        console.log("authgaurd created");

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean  {
        return true;
    }

}

受保护的模块和路线

//qa-routing.module.ts

const routes: Routes = 
[
  { 
    path: 'qa',      
    component: QAComponent,
    canActivate: [AuthGuard],

  }

];

@NgModule({

  imports: [
   RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class QARoutingModule { }


//qa.module.ts

@NgModule({
  imports: [
    QARoutingModule
  ],
  declarations: [
    QAComponent
  ],
  providers: [ ]
})
export class QAModule {}

2 个答案:

答案 0 :(得分:1)

嗯...是的,所以真正的问题:

我正在使用自举导航栏并使用href作为链接。每次我点击链接时,它会重新加载上下文,提供新的注入服务。更改了链接逻辑以使用router.navigate来解决。

答案 1 :(得分:0)

//app.module.ts

import {AuthService} from "./auth.service";
import { AuthGuard } from './auth-guard.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [ 
    QAModule,
    AppRoutingModule,
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }



//auth-guard.service

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(public authService: AuthService) {

        console.log("authgaurd created");

    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean  {
        return true;
    }

}