【问题标题】:Show/Hide components after checking the current page url检查当前页面 url 后显示/隐藏组件
【发布时间】:2019-10-25 01:27:52
【问题描述】:

我正在使用当前位置路径(如 homepageloginpagelogoutpage 搜索在我的 Angular 应用程序上显示/隐藏组件的最佳方式等。

我订阅了给我当前路径的路由器事件,所以如果我在登录页面中,我应该隐藏“导航栏组件”,如果我在主页中,我应该显示它。

这种方法应该适用于不同当前页面中的不同组件。所以我在想这个方法里面有个*ngIf

app.component.html

<nav *ngIf="myService.isComponentPartOfTheCurrentPage('navbar')">
   ...some navigation buttons here
</nav>

myService.ts

isComponentPartOfTheCurrentPage(componentName: string): boolean {
  const url = getCurrentPath(); // This works fine
  return currenPathContainsThisComponent(componentName, url); // This is gonna return true or false.
}

这种方法的主要问题是角度循环会多次调用此函数。我也读过一些不推荐这个王者的博客。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    在订阅您的路由事件时,使用当前更新服务上的行为主题

    section$ = new BehaviorSubject(null);
    

    在您的路线子中

    sections$.next(section);
    

    然后在您的组件中使用异步管道收听行为主题

    section$ = this.service.section$;
    

    在模板中

    <nav *ngIf="section$ | async as section">
       <div *ngIf="section === 'navbar'">Something</div>
    </nav>
    

    每次行为主体发出时,section 变量都会神奇地更新。

    【讨论】:

    • section值不应该是组件的名字,应该是url名字……比如:“login”、“home”、“logout”。 ...为什么?,因为'将在检查当前页面后显示/隐藏组件。示例:如果我在登录页面,我应该隐藏导航栏。
    【解决方案2】:

    您可以监视路由器事件,特别是NavigationEnd,将当前路由分配给一个可观察对象,然后在组件中检查我们当前所在的路由。

    服务:

    import { Router, NavigationEnd } from "@angular/router";
    import { filter, map } from "rxjs/operators";
    
    currentRoute$: Observable<string>;
    
    constructor(private router: Router) {
      this.currentRoute$ = router.events.pipe(
        filter(e => e instanceof NavigationEnd),
        map((e: NavigationEnd) => e.url)
      );
    }
    

    然后使用异步管道监听 observable 并进行检查

    *ngIf="(myService.currentRoute$ | async) === '/login'"
    

    如果您需要检查该网址片段是否包含在网址中,您也可以使用includes,然后您可以这样做:

    *ngIf="(myService.currentRoute$ | async).includes('login')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 2015-11-07
      • 2021-02-08
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多