angular - 如何制作 Angular2 Service 单例?

标签 angular singleton injectable angular2-guards

我正在尝试在我的应用程序中实现身份验证保护。 IE;只有经过身份验证的用户才能访问我的应用程序的某些路由。我正在关注给定的 here .

一旦用户登录,我将我的 AuthService 中的 bool 值更改为 true 以指示用户已登录。需要在应用程序的整个生命周期中保留该值。

源代码如下:

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

控制台输出

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

编辑: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 {}

我在这里做错了什么?任何帮助,将不胜感激。

最佳答案

如 ranakrunal9 所述,如果您在组件或指令中提供服务,您会为每个此类组件实例获得一个新实例。

您还会获得一个用于延迟加载模块的新实例(使用 loadChildren 加载)。延迟加载的模块有自己的根作用域和组件,如果服务是在延迟加载的模块中提供的,则此模块中的组件和服务将获得注入(inject)的服务的不同实例。

为确保您的整个应用程序只有一个实例,请仅在您的 AppModule 或由 AppModule 直接或间接使用 imports 加载的模块中提供它: [...].

另见 https://stackoverflow.com/a/40981772/217408

关于angular - 如何制作 Angular2 Service 单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41391998/

相关文章:

继承类上的 C# 单例模式

flutter - 你应该注入(inject)一个接口(interface)还是它的实现?

angular - @Injectable() 和 @Inject 有什么区别

dom - 检查用户是否在组件中的特定 div 内单击

database - AngularFire2 如何创建用户(名字、姓氏、电子邮件、密码)

http - Ionic 2 - Angular 2 http header 未随请求一起发送

angular - Angular 模板中的问号是什么?

c# - 状态很重要的对象的最佳设计模式 - 单例或静态

java并发-带有监视器线程的单例设计

angular - 无法将来自服务方法的数据显示到组件中