【问题标题】:Angular - Redirect to another component if conditions are not satisfiedAngular - 如果条件不满足,则重定向到另一个组件
【发布时间】:2021-01-19 20:38:58
【问题描述】:

我有一个组件,它是我登录后在项目中启动的第一个组件。我需要验证一些加载它的值。我试过这样: 在我调用帐户服务的 ngOnit 中,我将结果缓存到我需要在下一个服务中传递的属性中:“getCompanies”,然后我进行订阅。进入订阅我需要做一个控制:如果帐户 hasPrincipalRole 设置为 true 并且 getCompanies 的结果是一个空对象,我必须继续启动路线,否则我必须启动 getDashboard 服务。我对其进行了测试并且它可以工作,但每次都会发生 2-3 秒,我可以看到仪表板组件在重定向到“启动”路由之前加载。怎样才能避免这种情况?我在路由中遇到了与 canActivate 相同的问题,当我检查我是否被授权时,有几秒钟我看到了我无法查看的组件。哪个是最好的解决方案?

    this.accountService.identity().pipe(
      switchMap(account => {
        this.account = account;
        return this.sidebarService.getCompanies(this.account.id.toString());
      }))
      .subscribe(res => {
         if (this.account.hasPrincipalRole && Object.keys(res).length === 0) {
          this.router.navigateByUrl('/startup');
        }
        else {
          this.getDashboard(this.account.id);
        }
      }
    );

【问题讨论】:

    标签: angular


    【解决方案1】:

    在你的组件中添加一个属性/主题

    public isLoading = true;
    

    在你的 HTML 中添加一个 ngIf 到你的主 div

    <div *ngIf="!isLoading; else loading">
    ...
    </div>
    <div #loading>Loading</div>
    

    在您的订阅中,您在仪表板加载后设置变量(我不知道您的 getDashboard 做了什么,所以它可能必须放在其他地方)

     ...
     else {
          this.getDashboard(this.account.id);
          this.isLoading = false;
        }
    

    在某些情况下,使用 observable/subject 代替变量可能更容易控制

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多