2017-10-08 65 views
1

我试图按照此答案使我的身份验证服务成为单身人士。 Angular Service is reset on each call of itAngular - 身份验证服务作为单身人士

当用户登录时,我在我的AuthService中设置了一个isLoggedIn变量,希望保持这种状态。但是,当我navgiate受限制的路线,如/主。当用户登录时,变量在我的控制台中返回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}; 

} 

auth.guard.ts

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 

    } 
} 

app.module.ts

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

个shared.module.ts

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限制,为登录用户只)

import { NgModule }  from '@angular/core'; 
import { CommonModule } from '@angular/common'; 

import {MainComponent} from './main.component' 
import {ChatComponent} from '../chat/chat.component'; 
import {MomentsComponent} from '../moments/moments.component'; 
import {SettingsComponent} from '../settings/settings.component'; 
import {QuestionsComponent} from '../questions/questions.component'; 
import { SearchComponent } from '../search/search.component'; 
import { FormsModule } from '@angular/forms'; 

import {SharedModule} from '../../shared/shared.module'; 


import { MainRoutingModule }  from './main-routing.module'; 

@NgModule({ 
    imports: [ 
    CommonModule, 
    MainRoutingModule, 
    SharedModule, 
    FormsModule, 

    ], 
    declarations: [ 
    MainComponent, 
    ChatComponent, 
    MomentsComponent, 
    SearchComponent, 
    SettingsComponent, 
    QuestionsComponent, 
    ] 
}) 
export class MainModule {} 
+0

是页面刷新获得? – Sajeetharan

+0

是页面正在刷新 – KHAN

回答

1

由于页面被刷新,即使角服务是单身人士,这些值将在页面刷新时丢失。

或者,您可以在不刷新页面的情况下更改路线。或者你可以存储LoginStatuslocalstorage变量,并获得其他页面的信息,如果你真的想要的页面刷新发生

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

我明白谢谢你。 – KHAN

+0

我有麻烦,然后决定什么最好的方法是获得经过身份验证的用户。如果你看到这个问题https://stackoverflow.com/questions/46631207/angular-4-node-how-to-check-for-authenticated-user-using-auth-guard我无法调用后端服务及时检查用户是否已通过认证 – KHAN

+0

在app.module中提供服务(auth/guard)而不是共享模块 –