2016-12-30 16 views
7

Tôi đang cố gắng triển khai trình bảo vệ auth trong ứng dụng của mình. I E; Chỉ những người dùng được xác thực mới có thể truy cập các tuyến đường nhất định của ứng dụng của tôi. Tôi đang theo các tut cho here.Làm thế nào để làm cho Singular2 Service singleton?

Khi người dùng đăng nhập, tôi thay đổi giá trị boolean trong AuthService thành true để cho biết rằng việc sử dụng đã đăng nhập. Cần phải giữ lại thông tin đó trong suốt thời gian sử dụng ứng dụng.

Đưa ra dưới mã nguồn:

auth-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

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 => {} 
     ); 
    } 
} 

điều khiển đầu ra

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 

Edit: app.module.ts

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 {} 

Tôi đang làm gì sai ở đây? Bất kỳ trợ giúp sẽ được đánh giá cao.

+2

để làm singleton dịch vụ mà bạn phải thêm tất cả các dịch vụ của bạn trong 'phần providers' của 'modules' của bạn. Nếu bạn đã thêm các dịch vụ bên trong phần 'provider' của thành phần của bạn thì đối với cá thể dịch vụ thành phần đó sẽ được khởi tạo. – ranakrunal9

+0

Cho chúng tôi biết nơi bạn đã thêm dịch vụ này? App.module – Milad

Trả lời

3

Như đã đề cập bởi ranakrunal9, nếu bạn cung cấp dịch vụ tại một thành phần hoặc chỉ thị, bạn sẽ có được một cá thể mới cho mỗi cá thể thành phần như vậy.

Bạn cũng nhận được một phiên bản mới cho các mô-đun được nạp lười (được tải với loadChildren). Các mô-đun được nạp lười có phạm vi gốc và các thành phần và dịch vụ của riêng chúng trong mô-đun này sẽ nhận được một thể hiện khác của dịch vụ được tiêm nếu dịch vụ đó được cung cấp trong mô-đun được nạp lười đó.

Để đảm bảo bạn chỉ có một phiên bản duy nhất cho toàn bộ ứng dụng của mình, hãy cung cấp chỉ trong AppModule hoặc mô-đun được tải bởi AppModule trực tiếp hoặc gián tiếp sử dụng imports: [...].

Xem thêm https://stackoverflow.com/a/40981772/217408

+1

Tôi đã cung cấp 'AuthService' trong mô-đun phụ của tôi (Mô-đun quản trị). Như bạn đã đề xuất, tôi đã cung cấp 'AuthService' trong' AppModule', bây giờ mọi thứ hoạt động tốt. Cảm ơn bạn! –

+0

Bạn được chào đón. Vui mừng khi biết bạn có thể làm cho nó hoạt động. –

Các vấn đề liên quan