Javascript 角度2激活路线返回空

Javascript 角度2激活路线返回空,javascript,angular,Javascript,Angular,我正在尝试获取一个字符串,该字符串将告诉我用于访问页面的url——例如,如果有人导航到localhost/messages/inbox,我希望路由的“messages”部分作为字符串 到目前为止,我使用的代码是: import { Router, RouterModule, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-sub-nav', templateUrl:

我正在尝试获取一个字符串,该字符串将告诉我用于访问页面的url——例如,如果有人导航到localhost/messages/inbox,我希望路由的“messages”部分作为字符串

到目前为止,我使用的代码是:

    import { Router, RouterModule, ActivatedRoute } from '@angular/router';

    @Component({
      selector: 'app-sub-nav',
      templateUrl: './sub-nav.component.html',
      styleUrls: ['./sub-nav.component.css']
    })
    export class SubNavComponent implements OnInit {

      constructor(private router: ActivatedRoute) { }

      ngOnInit() {

         console.log(this.router.snapshot);

      }
   }
当我在控制台中查看时,它返回整个ActivateRoute对象,但大多数属性都是空的。包括快照、孩子、家长等。我缺少什么吗

只是一个简短的说明-我需要这个字符串在每次路线更改时更新。我以前确实使用过路由器对象,但每次路由更改时,它都会保持静态。

尝试:

this.router.data
      .subscribe(
         (data) => {
             console.log('data', data);
       });

您可以通过多种方式使用导航。所以我不是给你一个简单的答案,而是用这种方式来帮助你。我的应用程序是一个购物车,但这就是我如何搜索最畅销/最新重新定价的产品,并且只是普通搜索。在您的情况下,位置:/messages/inbox和searchStr=messageStr。这就是你的导航方式

goToMessage(searchStr: string){
if(this.productQuery.isTopSelling) 
  this._router.navigate(['/' + location + '/' + searchStr], 
    {queryParams: {isTopSelling: true}});
else if(this.productQuery.newPreRepurbished != 'none')
  this._router.navigate(['/' + location + '/' + searchStr], 
    {queryParams: {npr: this.productQuery.newPreRepurbished}});
else this._router.navigate(['/' + location + '/' + searchStr]);
}
下面是我从路由中检索信息的方法

   this.route.queryParams.subscribe(
    params=>{
      let messageStr =  params['id']; //how you retrieve the message
      let isTopSelling = params['isTopSelling'] || false; //search by boolean
      let newPreRepurbished = params['npr'] || 'none';
      let brand = params['brnd'] || 'none'; //search by string
    });
您可以使用queryParams向路由发送更多信息。我希望我没有把你弄糊涂。希望这有帮助。快乐编码

因为您得到的是一个静态答案(不改变),所以您可能需要实现OnChanges

ngOnChanges(){
  this.ngOnInit();
}
只是一个简短的说明-我需要这个字符串来更新每次路线 变化。我以前确实用过路由器对象, 但每次路线改变时,这似乎都保持不变

订阅路由器导航结束事件

NavigationEnd-表示导航成功结束时触发的事件

 ngOnInit() {
    this.router.events.subscribe(events => {
      if (events instanceof NavigationEnd) {
        console.log('NavigationEnd evnet', events);
      }
    })
  }
因此,每次成功导航到路由时,此事件都将使用事件对象触发:

{
 urlAfterRedirects: string
  toString(): string
  // inherited from router/RouterEvent
  id: number
  url: string
}

您能说明如何为该组件定义路由吗?还要检查什么是打印的console.log(this.router.snapshot.url)不,它只是一个空的阵列,工作得非常好!谢谢:)这是一个很好的例子,说明了为什么在if语句中应该使用大括号