2017-10-08 22 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)而不是共享模塊 –