微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何制作Angular2 Service单例?

我正试图在我的应用程序中实现一个auth guard.即;只有经过身份验证的用户才能访问我的应用的某些路由鉴于 here,我正在追踪啧啧.

一旦用户登录,我将我的AuthService中的布尔值更改为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加载).延迟加载的模块获得自己的根范围,如果在该延迟加载的模块中提供该服务,则此模块中的组件和服务将获得注入的服务的不同实例.

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

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

原文地址:https://www.jb51.cc/angularjs/141185.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐