每次调用Angular Service时都会重置

弗朗克·沙里尔

在我的Web Angular项目中,我创建了AuthenticationGuard和AuthenticationService来处理安全性。

这些文件来自我项目的另一个分支,该分支可以正常工作。

这是我的脚本的工作方式:

  1. 导航到“身份验证/登录”
  2. 用户输入他的凭证
  3. Authservice调用后端wepApi以获取Bearer令牌
  4. 后端返回令牌。
  5. AuthService将他的变量'isLoggedIn'设置为true;
  6. AuthService用于路由器导航到“ / home”
  7. AuthGuard通过检查AuthService的“ isLoggedIn”来检查身份验证。

我的问题是当AuthGuard访问AuthService时:AuthService总是返回false。

认证卫士

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

@Injectable()
export class AuthGuard 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 {
    if (this.authService.getIsLoggedIn()) { 
      return true; 
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

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

身份验证服务

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

import { config } from './../shared/smartadmin.config';

import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    public redirectUrl: string;

    constructor(private router: Router, private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // Always returns false
        return this.isLoggedIn;
    }

    public login(username: string, password: string) {
        this.ProcessLogin(username, password)
            .subscribe(result => {
                if (result === true) {
                    console.log("before attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns false
                    this.isLoggedIn = true;
                    console.log("after attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns true
                    this.router.navigate(this.redirectUrl ? [this.redirectUrl] : ['/home']);
                } else {
                    this.logout();
                }
            });
    }


    public logout(): void {
        localStorage.removeItem('oAuthToken');
        this.isLoggedIn = false;
    }

    private ProcessLogin(username: string, password: string): Observable<boolean> {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        let body = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

        let endpoint = config.API_ENDPOINT + 'token';

        return this.http.post(endpoint, body, options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().access_token;
                if (token) {
                    localStorage.setItem('oAuthToken', token);

                    // return true to indicate successful login
                    return true;
                } else {
                    localStorage.removeItem('oAuthToken');
                    // return false to indicate failed login
                    return false;
                }
            });
    }
}

汉普斯

在没有看到模块定义的情况下,我怀疑您没有将AuthService用作核心服务(单例),这意味着使用它的每个模块都将具有自己的实例(跟踪自己的isLoggedIn标志)。

为了使服务单角度,它必须由根模块注入器提供服务。为此,您需要执行以下操作:

import { NgModulep } from '@angular/core';
import { CommonModule, ModuleWithProviders } from '@angular/common';
import { AuthService, AuthGuard } from './services/index';

@NgModule({
  imports: [
    CommonModule,
    ModuleWithProviders
  ]
})
export class SharedModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard
      ]
    };
  }

}

然后,在将SharedModule导入根AppModule时,调用forRoot方法。

@NgModule({
  imports: [
    ...
    SharedModule.forRoot(),
    ...
  ],
  ...,
  bootstrap: [AppComponent]
})
export class AppModule { }

在这里https://angular.io/docs/ts/latest/guide/ngmodule.html#!#core-for-root看一下“配置核心服务”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

每次登录时bash提示都会重置

每次单击Angular都会进行API调用

每次加载组件时,Angular 4 路由都会调用 ngOnInit 重复 API 调用

LastKnownLocation 每次都会重置

为什么每次继续while循环时都会重置变量?

PHP SESSID在每次页面加载时都会重置

我每次使用UPDATE时,日期,时间都会重置

每次系统重新启动时,后台都会重置

Angular5 - 每次在页面上使用组件时都会调用 ngOnInit

每次点击都会重置DispatchQueue

每次调用notifyDataSetChanged()时,都会调用onBindViewHolder()

用于对列表进行排序的异步管道,每次有鼠标或键盘事件时都会调用 - Angular4

为什么每次点击UITextField时都会调用viewDidLayoutSubviews

每次从它调用方法时都会创建代理原型 bean

每次返回片段时都会调用livedata观察器

每次滚动时都会调用CustomAdapter getView()

每次调用Func时,UIView都会被覆盖-Swift

每次调用Func时,UIView都会被覆盖

每次渲染主体时都会调用SwiftUI Picker onReceive()

每次调用函数时,scrollTop都会复制值

每次使用变量时都会调用 PHP 函数吗?

每次调用函数时,Tkinter 规模都会卡住

Leaflet:每次地图移动或缩放时都会重置图层复选框状态

每次重新创建活动时,SharedPreference Set <String>都会重置

每次我重新启动EC2实例时,Magento base_url都会重置

每次我滚动经过触发点时,功能都会不断重置

每次我使用流浪汉时,流浪汉都会重置.vagrant目录

每次重新启动时,我的Debian / proc / cmdline都会重置

Android:每次将新对象添加到列表时,都会重置由列表填充的RecyclerView