本文介绍了如何使Angular2 Service单身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用程序中实现身份验证保护. IE;只有经过身份验证的用户才能访问我的应用的某些路由.我正在此处给出提示.

I'm trying to implement an auth guard in my app. ie; Only authenticated users can access certain routes of my app. I'm following the tut given here.

用户登录后,我将AuthService中的布尔值更改为true,以指示使用已登录.需要在应用程序的整个生命周期中保留该值.

Once the user is logged in I change a boolean value in my AuthService to true to indicate that the use has logged in. Which needs to be retained through out the life of app.

在源代码下方给出:

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

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

What am I doing wrong here? Any help would be appreciated.

推荐答案

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

As mentioned by ranakrunal9, if you provide a service at a component or directive, you get a new instance for each of such a component instance.

您还为延迟加载的模块(已加载loadChildren)获得了一个新实例.延迟加载的模块具有自己的根范围,并且如果该延迟加载的模块中提供了服务,则该模块中的组件和服务将获得注入的服务的不同实例.

You also get a new instance for lazy loaded modules (loaded with loadChildren). Lazy loaded modules get their own root scope and components and services within this module will get a different instance of a service injected if that service is provided within that lazy loaded module.

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

To ensure you only have a single instance for your whole application, provide it only in your AppModule or a module loaded by AppModule directly or indirectly using imports: [...].

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

这篇关于如何使Angular2 Service单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:02