Angular 2-Route Guard在浏览器刷新上不起作用 [英] Angular 2 - Route guard not working on browser refresh

查看:87
本文介绍了Angular 2-Route Guard在浏览器刷新上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在app.module.ts中定义了这些路由

Having these routes defined in app.module.ts

...
{ path: 'mypath', component: MyComponent, canActivate: [RouteGuard] }, 
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', redirectTo: '/home'}

和这项警卫服务

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AngularFire } from 'angularfire2';
import { AngularFireAuth } from 'angularfire2';

@Injectable()

export class RouteGuard implements CanActivate {

  private loggedIn: boolean;

  constructor ( private af: AngularFire, private auth: AngularFireAuth ) {}

  canActivate(): boolean {

    this.auth.subscribe(auth => {
      if  (auth)  { this.loggedIn = true; }
      else        { this.loggedIn = false; }
//          this.router.navigate(['/login']); for future implememtation
       });

    return this.loggedIn;
  }
}

从URL //mysite/mypath刷新浏览器,应用程序转到 //mysite而不是//mysite/mypath(并且还会跳过默认值 路线).

refreshing the browser from url //mysite/mypath the app goes to //mysite instead of //mysite/mypath (and also skips the default route).

在mypath路由上没有激活任何防护(例如:{ path: 'mypath', component: MyComponent }一切正常.

Without any guard activated on mypath route (ie: { path: 'mypath', component: MyComponent }everything works perfectly.

有人知道这是否是Angular错误吗? 我该如何避免这种行为?

Does anybody knows if this is an Angular bug ? How could I avoid this behaviour ?

我的开发环境是:

@angular/cli: 1.0.0-rc.1
node: 7.5.0
os: linux x64
@angular/cli: 1.0.0-rc.1
@angular/common: 2.4.9
@angular/compiler: 2.4.9
@angular/compiler-cli: 2.4.9
@angular/core: 2.4.9
@angular/flex-layout: 2.0.0-rc.1
@angular/forms: 2.4.9
@angular/http: 2.4.9
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 2.4.9
@angular/platform-browser-dynamic: 2.4.9
@angular/router: 3.4.9

感谢您的帮助.

PS:我试图在Stack Overflow或Github问题上都找到答案,而没有找到答案.我看到了类似的问题 Angular 2路由在页面上不起作用用Apache刷新,但这不是我的情况.

PS: I have tried to find an answer both on Stack Overflow or on Github issues without finding an answer. I saw a similar question Angular 2 routing not working on page refresh with Apache, but this is not my case.

推荐答案

您可以将异步结果发送给路由保护器:

you can an asynchronous result to the route guard :

 canActivate(): Promise<boolean> {
   let self = this;
    return this.auth.toPromise().then(auth => {
         if  (auth)  { self.loggedIn = true; }
         else { self.loggedIn = false; }

         self.router.navigate(['/login']); for future implememtation

        return self.loggedIn;
    });


}

这篇关于Angular 2-Route Guard在浏览器刷新上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆