如何在角度4应用程序中刷新浏览器后重新加载相同的组件

时间:2018-05-08 16:54:05

标签: javascript angular

应用程序名称:登录应用程序

基本上我是通过登录组件(http://localhost:4200/login)登录应用程序的。如果用户在我的对象中传递,它会将其重定向到admin组件。这运行良好。但是只要我在admin(http://localhost:4200/admin)上刷新页面。我被重定向回登录(http://localhost:4200/login)页面。即使我已成功登录。

这是必要的代码。

auth.service.ts

import { Injectable } from '@angular/core';
import { UserModel } from './user';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

const USERS = [
  {username: 'admin', password: '12345', role: 'ADMIN'},
  {username: 'user', password: '67890', role: 'USER'}
]

let userObservable = Observable.of(USERS);

@Injectable()
export class AuthService {

  constructor() { }

  private loginUrl = '/login';
  private redirectUrl = '/admin';
  private loggedInUser: UserModel;
  private isLoggedIn: boolean = false; //This is the value I am making true/false
  getAllUsers(): Observable<UserModel[]> {
    return userObservable;
  }

  isAuthenticated(username: string, password: string): Observable<boolean> {
    return this.getAllUsers()
      .map(users => {
        let user = users.find(user => (user.username === username) && (user.password === password));
        if(user) {
          this.isLoggedIn = true; 
          this.loggedInUser = user;
        } else {
          this.isLoggedIn = false; 
        }
        return this.isLoggedIn; // boolean value to use found user
      })
  }

  isUserLoggedIn() {
    return this.isLoggedIn;
  }

  getRedirectUrl() {
    return this.redirectUrl;
  }

  setRedirectUrl(url) {
    this.redirectUrl = url;
  }

  getLoginUrl() {
    return this.loginUrl;
  }

  getLoggedInUser(): UserModel {
    return this.loggedInUser;
  }

  logoutUser(): void {
    this.isLoggedIn = false;
  }

}

AUTH-guard.service.ts

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

@Injectable()
export class AuthGuardService implements CanActivate {

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

  canActivate(activatedRoute: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
    let url: string = routerState.url;
    let user = this.authService.getLoggedInUser();
    if(this.authService.isUserLoggedIn()) {
      return true;
    }
    this.authService.setRedirectUrl(url);
    this.router.navigate([this.authService.getLoginUrl()])
    return false;
  }

}

login.component.html

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <p>
    <label for="">Username&nbsp;</label><input type="text" formControlName="username">
  </p>
  <p>
    <label for="">Password&nbsp;</label><input type="text" formControlName="password">
  </p>
  <button>Submit</button>
</form>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AuthService } from '../assets/auth.service';

@Component({
  selector: 'la-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

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

  ngOnInit() {
  }
  loginForm = new FormGroup({
    username: new FormControl(),
    password: new FormControl()
  })

  onSubmit(){
    let uname = this.loginForm.get('username').value;
    let pass = this.loginForm.get('password').value;

    this.authService.isAuthenticated(uname, pass).subscribe(
      (authenticated) => {
        if(authenticated) {
          let url = this.authService.getRedirectUrl();  

          this.router.navigate([url]);
        }
      }
    )
  }    
}

app.routing.module

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { AdminComponent } from './admin/admin.component';
import { UserComponent } from './user/user.component';
import { AuthGuardService } from './assets/auth-guard.service';

const routes: Routes = [
    {'path': '', redirectTo: '/login', pathMatch: 'full'},
    {'path': 'login', component: LoginComponent},
    {'path': 'admin', component: AdminComponent, canActivate: [ AuthGuardService ]},
    {'path': 'user', component: UserComponent}
]

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [RouterModule]
})

export class RoutingModule {}

在浏览器上按下刷新按钮后重定向到登录页面的原因:这是因为当我按下刷新应用程序时。它重新加载每个和auth.service(isLoggedIn:boolean = false)是应用程序在重新加载应用程序时获得的。请将我退出应用程序。

My Startegy:我使用@ ngx-pwa / local-storage设置并获得这样的值

//在succesfull login上设置值

this.localStorage.setitem('token','isLoggedIn).subscribe(()=>{})

//在canActivate方法中获取刷新值。如果值匹配返回true并且管理组件加载,则应将其与字符串值进行比较

this.localStorage.getitem('token').subscribe((res)=>{ console.log(res) // how to use this value outside of this scope so to compare it with string metioned below})

这是 login.component.ts

的更新代码
onSubmit(){
    let uname = this.loginForm.get('username').value;
    let pass = this.loginForm.get('password').value;

    this.authService.isAuthenticated(uname, pass).subscribe(
      (authenticated) => {
        if(authenticated) {
          let url = this.authService.getRedirectUrl();
          let user = this.authService.getLoggedInUser();

          this.localStorage.setItem('token', 'isLoggedIn').subscribe(()=>{});

          this.router.navigate([url]);
          console.log(user)
        }
      }
    )

这是 auth.gaurd服务

的更新代码
    checkIsLoggedIn: string;
    canActivate(activatedRoute: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) {
        let url: string = routerState.url;
        let user = this.authService.getLoggedInUser();
        this.localStorage.getitem('token').subscribe(
   (res) => { this.checkIsLoggedIn = res } 
)
        if(this.checkIsLoggedIn == 'IsLoggedIn' //here it is getting undefined the value never goes out ) {
          return true;
        }
        this.authService.setRedirectUrl(url);
        this.router.navigate([this.authService.getLoginUrl()])
        return false;
      }

如何在此应用程序中管理应用程序的状态,以便刷新不会破坏视图。或者如果可能的话,如何使用@ngrx localstorage来设置/获取值并在canActivate方法中进行比较,或者还有其他方法。

0 个答案:

没有答案