首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角路由器对浏览器url没有正确的响应

角路由器对浏览器url没有正确的响应
EN

Stack Overflow用户
提问于 2017-08-08 09:59:21
回答 1查看 332关注 0票数 0

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

app-routing.module.ts

代码语言:javascript
复制
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:

代码语言:javascript
复制
canActivate() {
        this._mysvc.isAuthorized().subscribe(data => this.auth = data);
        if (!this.auth) {
            this._router.navigate(['/']);
        }
        return this.auth;
    }

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

public.component.ts:

代码语言:javascript
复制
    isAuthorized(authorized:boolean):void {
        if (authorized) {
          this._router.navigate(['/start']);
        }
      }
  ngOnInit():void {
    this._mysvc.isAuthorized().subscribe(this.isAuthorized.bind(this), this.isAuthorizedError);
  }

index.html:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-08 10:33:40

问题是async请求,您将其处理为sync

代码语言:javascript
复制
canActivate(): Observable<boolean> {
  return this._mysvc.isAuthorized().do((auth: boolean) => {
     if (!auth) {
       this._router.navigate(['/']);
     }
  });
}

为此,您需要导入do操作符:

代码语言:javascript
复制
import 'rxjs/add/operator/do'

或者:

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

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

代码语言:javascript
复制
import 'rxjs/add/operator/toPromise';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45565261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档