Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 作为单例的角度身份验证服务_Angular - Fatal编程技术网

Angular 作为单例的角度身份验证服务

Angular 作为单例的角度身份验证服务,angular,Angular,我试图按照这个答案使我的身份验证服务成为一个单例 当用户登录时,我在AuthService中设置了一个isLoggedIn变量,希望保持这种状态。但是,当我导航到一条受限路线时,如/main。当用户实际登录时,该变量在我的控制台中返回false 我做错了什么 auth.service.ts import { JwtService } from './jwt.service'; import { Injectable } from '@angular/core'; import { ApiServ

我试图按照这个答案使我的身份验证服务成为一个单例

当用户登录时,我在AuthService中设置了一个isLoggedIn变量,希望保持这种状态。但是,当我导航到一条受限路线时,如/main。当用户实际登录时,该变量在我的控制台中返回false

我做错了什么

auth.service.ts

import { JwtService } from './jwt.service';
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { UserService } from './user.service';

@Injectable()
export class AuthService {

  user: any;
  isLoggedIn: boolean = false;

  constructor(
    private apiService: ApiService,
    private jwtService: JwtService,
    private userService: UserService) {
  }

  login(credentials) {

    let endpoint = 'auth/'

    return this.apiService.post(endpoint, credentials)
      .map(res => {
        this.jwtService.saveToken(res.data.jwtToken);
        window.localStorage.setItem('user_id', res.data.user._id);
        this.user = res.data;
        this.isLoggedIn = true;
      });
  }

  logout() {

  }

  isAuthenticated(): boolean {return this.isLoggedIn};

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

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private authService: AuthService, private router: Router) { }


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


    console.log(this.authService.isAuthenticated());
    if (this.authService.isAuthenticated()) {
      return true;
    }


    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false

  }
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';


import {AppRoutingModule} from './app-routing.module';

import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component'
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { MainComponent } from './components/main/main.component';


import {ApiService} from './services/api.service';
import {JwtService} from './services/jwt.service';
import {UserService} from './services/user.service';
import {SharedModule} from './shared/shared.module';



@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    LoginComponent,

  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    SharedModule.forRoot(),
  ],
  providers: [
    ApiService,
    JwtService,
    UserService,
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }
import {ModuleWithProviders, NgModule} from '@angular/core';
import {MaterialModule} from './material.module';
import { FlexLayoutModule } from "@angular/flex-layout";

import {AuthGuard} from '../guards/auth.guard';
import { AuthService } from '../services/auth.service';

@NgModule({
  imports: [
    MaterialModule,
    FlexLayoutModule,

  ],
  exports: [
    MaterialModule,
    FlexLayoutModule,    
  ]
})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard,
      ]
    };
  }
}
auth.guard.ts

import { JwtService } from './jwt.service';
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { UserService } from './user.service';

@Injectable()
export class AuthService {

  user: any;
  isLoggedIn: boolean = false;

  constructor(
    private apiService: ApiService,
    private jwtService: JwtService,
    private userService: UserService) {
  }

  login(credentials) {

    let endpoint = 'auth/'

    return this.apiService.post(endpoint, credentials)
      .map(res => {
        this.jwtService.saveToken(res.data.jwtToken);
        window.localStorage.setItem('user_id', res.data.user._id);
        this.user = res.data;
        this.isLoggedIn = true;
      });
  }

  logout() {

  }

  isAuthenticated(): boolean {return this.isLoggedIn};

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

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private authService: AuthService, private router: Router) { }


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


    console.log(this.authService.isAuthenticated());
    if (this.authService.isAuthenticated()) {
      return true;
    }


    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false

  }
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';


import {AppRoutingModule} from './app-routing.module';

import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component'
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { MainComponent } from './components/main/main.component';


import {ApiService} from './services/api.service';
import {JwtService} from './services/jwt.service';
import {UserService} from './services/user.service';
import {SharedModule} from './shared/shared.module';



@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    LoginComponent,

  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    SharedModule.forRoot(),
  ],
  providers: [
    ApiService,
    JwtService,
    UserService,
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }
import {ModuleWithProviders, NgModule} from '@angular/core';
import {MaterialModule} from './material.module';
import { FlexLayoutModule } from "@angular/flex-layout";

import {AuthGuard} from '../guards/auth.guard';
import { AuthService } from '../services/auth.service';

@NgModule({
  imports: [
    MaterialModule,
    FlexLayoutModule,

  ],
  exports: [
    MaterialModule,
    FlexLayoutModule,    
  ]
})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard,
      ]
    };
  }
}
共享的.module.ts

import { JwtService } from './jwt.service';
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { UserService } from './user.service';

@Injectable()
export class AuthService {

  user: any;
  isLoggedIn: boolean = false;

  constructor(
    private apiService: ApiService,
    private jwtService: JwtService,
    private userService: UserService) {
  }

  login(credentials) {

    let endpoint = 'auth/'

    return this.apiService.post(endpoint, credentials)
      .map(res => {
        this.jwtService.saveToken(res.data.jwtToken);
        window.localStorage.setItem('user_id', res.data.user._id);
        this.user = res.data;
        this.isLoggedIn = true;
      });
  }

  logout() {

  }

  isAuthenticated(): boolean {return this.isLoggedIn};

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

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private authService: AuthService, private router: Router) { }


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {


    console.log(this.authService.isAuthenticated());
    if (this.authService.isAuthenticated()) {
      return true;
    }


    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false

  }
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';

import { AppComponent } from './app.component';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';


import {AppRoutingModule} from './app-routing.module';

import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component'
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { MainComponent } from './components/main/main.component';


import {ApiService} from './services/api.service';
import {JwtService} from './services/jwt.service';
import {UserService} from './services/user.service';
import {SharedModule} from './shared/shared.module';



@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    RegisterComponent,
    LoginComponent,

  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    SharedModule.forRoot(),
  ],
  providers: [
    ApiService,
    JwtService,
    UserService,
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }
import {ModuleWithProviders, NgModule} from '@angular/core';
import {MaterialModule} from './material.module';
import { FlexLayoutModule } from "@angular/flex-layout";

import {AuthGuard} from '../guards/auth.guard';
import { AuthService } from '../services/auth.service';

@NgModule({
  imports: [
    MaterialModule,
    FlexLayoutModule,

  ],
  exports: [
    MaterialModule,
    FlexLayoutModule,    
  ]
})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        AuthService,
        AuthGuard,
      ]
    };
  }
}
main.module.ts(受auth.guard限制,仅限登录用户)


由于页面被刷新,即使angular服务是单例的,这些值也会在页面刷新时丢失

或者,您可以只更改路由而不刷新页面。或者,您可以将
LoginStatus
存储在
localstorage
变量上,并在其他页面上获取信息(如果确实希望进行页面刷新)

this.isLoggedIn = true;
localStorage.setItem('isLoggedIn', 'true');

页面正在刷新吗?是的,页面正在刷新。我很难确定获取经过身份验证的用户的最佳方法。如果您看到这个问题,我无法及时调用后端服务,以检查用户是否经过身份验证。在app.module中提供服务(auth/guard),而不是共享module@KHAN如果您正在处理令牌,则不必再次调用以检查用户是否经过身份验证。我已经回答了这个问题