Logout仍然显示Angular 4中的侧边栏和标题

时间:2017-09-05 03:18:18

标签: angular authentication angular-routing angular-services

我正在尝试创建管理信息中心。首先,您将被重定向到登录屏幕,成功登录后,您将看到管理仪表板。问题依赖于我点击标题上的注销按钮后,我可以看到侧边栏和标题?我应该被单独重定向到登录屏幕。有关如何构建或如何解决此问题的任何帮助?

  

app.component.html

<ng-template [ngIf]="authService.isLoggedIn()">
<app-header></app-header>
<app-sidebar></app-sidebar>  
</ng-template>
<router-outlet></router-outlet>
  

app.component.ts

import{ NgModule } from '@angular/core';
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { SigninComponent } from './auth/signin/signin.component';
import { AuthGuard } from './auth/auth-guard.service';

const appRoutes: Routes = [
    { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
    { path: 'signin', component: SigninComponent },
    { path: 'users', loadChildren: './user/user.module#UserModule', canActivate: [AuthGuard]},
    { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard]},
];


@NgModule({
    imports: [RouterModule.forRoot(appRoutes, {preloadingStrategy: PreloadAllModules})
    ],

    exports: [RouterModule]
})

export class AppRoutingModule {

}
  

header.component.html

<nav class="navbar">
  <div class="container-fluid">
    <div class="navbar-header">
      <a routerLink="/" class="navbar-brand">Admin Dashboard</a>
    </div>
    <button class="btn btn-danger" style="cursor: pointer;" (click)="onSignOut()">Logout</button>
  </div>
</nav>
<br>
  

header.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../auth/auth.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  constructor(private authService: AuthService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
  }

  onSignOut(){
      this.authService.logout();
      this.router.navigate(['/signin']);

  }
}
  

auth.service.ts

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


@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private http: Http) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  signinUser(email: string, password: string) {  
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
    .post(
      'http://sample/auth/login', 
      JSON.stringify({ email, password }), 
      { headers }
      )
    .map(
        response => {
          localStorage.setItem('auth_token', response.json().id_token);
          this.loggedIn = true;
          console.log(response);
        },
        error => {
          alert(error.text());
          console.log(error.text());
        }
      );

   }

   isLoggedIn() {
    return this.loggedIn;
  }

   logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('auth_token');
    }
}

1 个答案:

答案 0 :(得分:1)

auth服务使用变量loggedIn来确定用户是否已登录。这是用于确定标题和侧边栏是否可见的变量。注销时此变量不会更新,即使在您注销后也会继续返回true。

更新您的注销方法以设置正确的登录状态:

logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('auth_token');
    this.loggedIn = false;
}