【问题标题】:How to check if the route child is exist - Angular如何检查子路由是否存在 - Angular
【发布时间】:2020-01-16 10:16:02
【问题描述】:

如果用户移动到错误的子路径,我会尝试重定向用户。我已经为向 api 请求数据的子组件创建了保护,但我不确定如果数据不存在如何重定向用户。如果数据不存在或重定向到主页,我想为用户显示 404。抱歉,如果重复,但我找不到解决方案。

场景:

  1. 用户必须传递密码才能重定向到他的电影。 (身份验证服务)
 public login(password: string) {
    firebase.database().ref("clients")
      .orderByChild("password").equalTo(password).once("value", snapshot => {
        if (snapshot.exists()) {
          const route = Object.keys(snapshot.val())[0];
          this.router.navigate(["/strefa-klienta", route]);
        } else {
          this._snackBar.open(
            "Podano błędne hasło. Spróbuj jeszcze raz.",
            "Zamknij",
            { duration: 2000 }
          );
        }
      });
  }
  1. 如果通过,用户将被重定向到他的路由页面和数据的保护请求(保护)
canActivate(
    child: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    return this.clientsState.loading$.pipe(
      map(loading => {
        if (!loading) {
          this.clientsState.load(child.url[0].path);
        }
        return true;
      }),
      take(1)
    );
  }
}

这是我的 app-routing.module


{
   path: "strefa-klienta",
   children: [
     {
       path: "",
       pathMatch: "full",
       redirectTo: "/"
     },
     {
       path: ":id",
       component: components.ClientSiteComponent,
       canActivate: [guards.ClientGuard]
     },
   ],
}

例如。我有 2 个用户 [John, Rick] ("/strefa-klienta/John")。如果有人会尝试查找不存在“Anna”(“/strefa-klienta/Anna”)的用户,我想显示 404。

感谢您的帮助

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    我认为你必须在你的 app-routing.module 中添加这个

    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: '**', redirectTo: 'home', pathMatch: 'full' }
    

    【讨论】:

    • 我之前尝试过,但并没有改变任何东西。在路径中我可以写随机参数,它仍然会路由。 (/strefa-klienta/example_text)。
    猜你喜欢
    • 2016-07-08
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2021-09-24
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多