使用在导航中使用路由选择的页面

  • 本文关键字:导航 路由选择 angular
  • 更新时间 :
  • 英文 :


我是Angular的新手,并且以身作则。我创建了一个使用Selector在App.ponent中调用的NAV组件,我想做的是在我的导航组件中隐藏一些列表条目,具体取决于我正在路由的页面。例如,如果我以示例导航到"登录"页面,我无法确定的事情是如何将变量" ShowLogin"设置为True。我可以肯定的是,NAV组件甚至在登录组件启动之前就可以创建。我认为服务是必经之路的?我正在使用Angular 7。

如果您要路由不需要登录但需要更改nav bar中的显示项目的不同页面,那么我认为您不需要服务。在您的NAV-Component中注入Router并收听路由器NavigationEnd事件。

ngOnInit() {
  // Router is injected in the constructor and the variable name is _router
  this._router.events.pipe(
    filter(event => event instanceof NavigationEnd))
    .subscribe(
        (data: NavigationEnd) => {
            // set your flag here depending on the url
            console.log(data.url)
        }
    );
}

如果要根据状态登录的登录到NAV组件上的项目,则可以使用服务(可能使用localStorage或cookie(,并使用简单的属性绑定到服务的更新属性,您可以删除/在NAV组件中添加项目。

我意识到我必须将路由器的实例声明为构造函数的一部分。因此,由于xyz。

,以下作用100%
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
  selector: 'nav-menulist',
  templateUrl: './menulist.component.html',
  styleUrls: ['./menulist.component.css']
})
export class MenulistComponent implements OnInit {
  constructor(private myservice: VariableService, private _router?: Router) { }
  ngOnInit() {
    this._router.events.pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(
          (data: NavigationEnd) => {
              // set your flag here depending on the url
              console.log(data.url)
          }
      );
  }
}

最新更新