2016-12-30 4 views
7

내 앱에 인증 가드를 구현하려고합니다. 즉; 인증 된 사용자 만 내 앱의 특정 경로에 액세스 할 수 있습니다. 나는 here 주어진 주어진 혀를 따르고있어.Angular2 Service 싱글 톤을 만드는 방법은 무엇입니까?

일단 사용자가 로그인하면 내 AuthService의 부울 값이 true로 변경되어 사용이 로그인되었음을 나타냅니다. 앱 수명 기간 동안 유지해야하는 항목이 있습니다. 소스 코드 아래

:

인증-guard.service.ts

import { Injectable }  from '@angular/core'; 
import { 
    CanActivate, Router, 
    ActivatedRouteSnapshot, 
    RouterStateSnapshot 
}      from '@angular/router'; 
import { AuthService } from './auth.service'; 

@Injectable() 
export class AuthGuardService implements CanActivate { 
    constructor(private authService: AuthService, private router: Router) {} 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {   
    let url: string = state.url; 
    return this.checkLogin(url); 
    } 

    checkLogin(url: string): boolean { 
    console.log('Auth Guard Service: ' + this.authService.isLoggedIn); 
    if (this.authService.isLoggedIn) { return true; } 
    // Store the attempted URL for redirecting 
    this.authService.redirectUrl = url; 

    // Navigate to the login page with extras 
    this.router.navigate(['/admin', 'admin-login']); 
    return false; 
    } 
} 

auth.service.ts

import { Injectable } from '@angular/core'; 
    import { Http } from '@angular/http'; 

    import { User } from '../user/shared/user.model'; 

    import { ServiceBase } from '../../core/service.base'; 
    import { appConfig } from '../../core/app.config'; 

    @Injectable() 
    export class AuthService extends ServiceBase { 
     public isLoggedIn: boolean = false; 
     redirectUrl: string; 
     apiUrl: string; 
     constructor(private http: Http) { 
      super(); 
      this.apiUrl = appConfig.apiBaseUrl + '/users/signin'; 
     } 
     signin(user: User, successCallback, errorCallback) { 
      return this.http.post(this.apiUrl, user).subscribe(
       res => { 
        this.isLoggedIn = true; 
        successCallback(res); 
       }, 
       err => { 
        //this.isLoggedIn = false; 
        errorCallback(err); 
       } 
      ); 
     }    
    } 

login.component.ts

(210)
import { Component, OnInit } from '@angular/core'; 
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; 
import { Router } from '@angular/router'; 
import { User } from '../../user/shared/user.model'; 
import { AuthService } from '../auth.service'; 

@Component({ 
    moduleId: module.id, 
    templateUrl: 'login.component.html' 
}) 
export class AdminLoginComponent implements OnInit{ 

    user: User; 
    userLoginForm: FormGroup; 

    constructor(
     private formBuilder: FormBuilder, 
     private authService: AuthService, 
     private router: Router){ 
     this.user = new User(); 
    } 

    ngOnInit(){ 
     this.buildLoginForm(); 
    } 
    buildLoginForm() { 
     ... 
    } 
    login() { 
     if(!this.userLoginForm.valid) return false; 
     this.authService.signin(this.user, 
      response => { 
       console.log('Login Component: ' + this.authService.isLoggedIn); 
       this.router.navigate(['/admin', 'products']); 
      }, 
      response => {} 
     ); 
    } 
} 

콘솔 출력

XHR finished loading: POST "http://localhost:3000/api/users/signin". 
login.component.ts:40 Login Component: true 
auth-guard.service.ts:23 Auth Guard Service: false 

편집 : 내가 잘못 여기서 뭐하는 거지

import { NgModule } from '@angular/core'; 
    ... 
    import { AuthGuardService } from './auth/auth-guard.service'; 
    import { AuthService } from './auth/auth.service'; 

    @NgModule({ 
     imports: [ 
      ... 
      AdminRoutingModule 
     ], 
     exports: [ 
     ], 
     declarations: [ 
      ... 
      AdminLoginComponent, 
      ... 
     ], 
     providers: [ 
      AuthGuardService, 
      AuthService, 
      ... 
     ], 
     bootstrap:[] 
    }) 
    export class AdminModule {} 

을 app.module.ts? 어떤 도움을 주시면 감사하겠습니다.

+2

참조하십시오. 구성 요소의'providers' 섹션에 서비스를 추가 한 경우 해당 구성 요소에 대해 새 서비스 인스턴스가 초기화됩니다. – ranakrunal9

+0

어디에서이 서비스를 추가했는지 보여주십시오. App.module – Milad

답변

3

ranakrunal9에서 언급했듯이 구성 요소 또는 지시문에 서비스를 제공하면 해당 구성 요소 인스턴스마다 새로운 인스턴스가 생성됩니다.

또한 지연로드 모듈 (loadChildren이로드 됨)에 대한 새 인스턴스를 얻습니다. 지연로드 모듈은 고유 한 루트 범위를 가지며이 모듈 내 구성 요소와 서비스는 해당 지연로드 모듈 내에 서비스가 제공되는 경우 주입 된 다른 서비스 인스턴스를 가져옵니다.

전체 응용 프로그램에 대해 단일 인스턴스 만 사용하려면 AppModule 또는 AppModule에 의해로드 된 모듈을 imports: [...]을 사용하여 직접 또는 간접적으로 제공하십시오.

당신이 당신의`modules`의 providers` 섹션`내에서 모든 서비스를 추가해야 할 서비스의 싱글을하는 것도 https://stackoverflow.com/a/40981772/217408

+1

서브 모듈 (Admin Module)에 'AuthService'를 제공했습니다. 필자가'AppModule'에'AuthService'를 제공해 주겠다고 제안 했으므로 모든 것이 잘 작동합니다. 고맙습니다! –

+0

당신을 진심으로 환영합니다. 당신이 듣기 좋다 니 일하게 만들 수 있습니다. –

관련 문제