【问题标题】:Angular router doesn't respond properly for browser urlAngular 路由器无法正确响应浏览器 url
【发布时间】:2017-08-08 09:59:21
【问题描述】:

我的问题是,当我在浏览器中更改 url 时,它总是指向起始路由,当我键入路由器中存在的路径以外的其他内容时,我得到 404。

app-routing.module.ts

const routes: Routes = [
  {path: "start", canActivate:[RoutingGuard], component: Start},
  {path: "path-1", canActivate:[RoutingGuard], component: One},
  {path: "path-2", canActivate:[RoutingGuard], component: Two},
  {path: "path-3", canActivate:[RoutingGuard], component: Three},
  {path: "path-4", canActivate:[RoutingGuard], component: Four},
  {path: "", component: Public},
  {path: "**", redirectTo: "", pathMatch:'full'}
];

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

routing-guard.service.ts:

canActivate() {
        this._mysvc.isAuthorized().subscribe(data => this.auth = data);
        if (!this.auth) {
            this._router.navigate(['/']);
        }
        return this.auth;
    }

我有一个登录名,并且在公共组件中我有这个方法,如果用户登录,我会重定向到 /start。

public.component.ts:

    isAuthorized(authorized:boolean):void {
        if (authorized) {
          this._router.navigate(['/start']);
        }
      }
  ngOnInit():void {
    this._mysvc.isAuthorized().subscribe(this.isAuthorized.bind(this), this.isAuthorizedError);
  }

index.html:

<html lang="en">
<head>
  <base href="/">

  <!--<meta charset="UTF-8">-->
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
  <app-root></app-root>
</body>
</html>

我使用重写配置,所以我跳过了 url 中的 #

rewrite.config:

RewriteRule /start/? /index.html [NC]
RewriteRule /path-1/? /index.html [NC]
RewriteRule /path-2/? /index.html [NC]
RewriteRule /path-3/? /index.html [NC]
RewriteRule /path-4/? /index.html [NC]

【问题讨论】:

  • 您能给我们看看 RoutingGuard 的代码吗?也许有重定向到 /start/?如果您在路由保护中调用“isAuthorized”并且您已登录,那么您当然每次都会被重定向到 /start/。把它转过来检查 !authorized
  • @MeMeMax 我在问题中添加了 routingGuard 代码!
  • 你的守卫中的“this._mysvc.isAuthorized()”是否与公共组件中的方法相同?
  • 是的,它是订阅 mysvc.isAuthorized() 的结果,我将编辑我的代码并显示它!谢谢

标签: angular angular2-router


【解决方案1】:

问题是您处理为sync 的async 请求:

canActivate(): Observable<boolean> {
  return this._mysvc.isAuthorized().do((auth: boolean) => {
     if (!auth) {
       this._router.navigate(['/']);
     }
  });
}

为此,您需要导入do 运算符:

import 'rxjs/add/operator/do'

或者:

async canActivate(): Promise<boolean> {
  if (!await this._mysvc.isAuthorized().toPromise()) {
     this._router.navigate(['/']);
  }
  return auth;
}

为此,您需要导入 toPromise 运算符

import 'rxjs/add/operator/toPromise';

【讨论】:

  • 我收到此错误消息,试图构建“属性 'do' 在类型 'Observable 上不存在”,第二种方式我如何设置 auth 的值?
  • 我已经更新了我的答案,如果您使用的是angular-cli,您可以将这些导入添加到您的polyfills.ts
  • 谢谢它现在似乎工作正常!我想知道为什么我应该在 pollyfills.ts 中导入这个“import 'rxjs/add/operator/do'”?我在 routing-gaurd.service.ts 中导入了它!
  • 因为这样你只需要导入一次,并且你有一个通用文件,你可以在需要的时候添加更多的操作符
猜你喜欢
  • 2016-09-09
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2015-05-06
  • 2018-12-09
  • 2018-10-17
相关资源
最近更新 更多