【问题标题】:Angular get current route param within a promise? [duplicate]Angular 在承诺中获取当前路由参数? [复制]
【发布时间】:2019-08-02 11:22:58
【问题描述】:

我需要在我的 ngOnInit 中以 promise 的形式获取当前路由 id,并且在获得 id 值后,我想继续使用该 id。

我尝试过这样的事情:

var temp = this.route.snapshot.paramMap.get('id');

// and doing something with it here

this.route.params.toPromise().then(data => {
// doing something with it here
});

遗憾的是,它始终为空,即使我的网址类似于“localhost:4200/answer/1248523” 它需要发生在 ngOnInit 内部。 如何异步获取当前id?

我创建了一个导航栏来在我的 app.component.html 中的不同组件之间切换,基本上我想在组件之间切换/执行路由时保留 paramId。

<nav mat-tab-nav-bar mat-align-tabs="center">
    <a mat-tab-link *ngFor="let link of navLinks" [routerLink]="link.link" routerLinkActive #rla="routerLinkActive"
        [active]="rla.isActive">
        {{link.label}}
    </a>
</nav>
<router-outlet></router-outlet>

我的组件.ts

constructor(private router: Router,private route: ActivatedRoute) {
    this.navLinks = [
      {
        label:'info',
        link:'./information',
        index:0
      }, {
        label: 'theme',
        link:'./theme',
        index:1
      },
      {
        label: 'form',
        link: './form',
        index: 2
      }, {
        label: 'attach',
        link: './attach',
        index: 3
      }, {
        label: 'testSum',
        link: './testSum',
        index: 4
      },
    ];
  }

  ngOnInit(): void {
    var paramId = this.route.snapshot.paramMap.get('id');
    this.router.events.subscribe((res) => {

      if(this.router.url.indexOf("answer") !== -1) {
        this.navLinks = [
          {
            label: 'Summary',
            link: './answer/:id',
            index: 0
          }, {
            label: 'Inbox',
            link: ['./inbox',paramId],
            index: 1
          }
        ];
      }  
      this.activeLinkIndex = this.navLinks.indexOf(this.navLinks.find(tab => tab.link === '.' + this.router.url));
    });
  }

我的路由也在寻找收件箱,答案是这样的:

{ path: 'answer/:id', component: AnswerSummaryComponent},
{ path: 'inbox/:id', component: InboxComponent}

所以基本上导航栏有一个标准的导航数组(信息、主题、表单、附件、testSum),但如果有人使用 (localhost:4200/answer....) 之类的链接访问站点/应用程序,它应该显示不同的导航。这工作得很好。
如果有人访问该网站,让我们说:localhost:4200/answer/123123 他会看到摘要组件,如果他导航到收件箱,我希望 url 保持“localhost:4200/inbox/123123”,但 url 更改为“localhost :4200/收件箱”。所以我想在链接(对象属性)本身中传递当前当前的 idParam。

【问题讨论】:

标签: javascript angular asynchronous


【解决方案1】:

你应该这样做:

import { ActivatedRoute } from '@angular/router';

...

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {
    this.route.params.subscribe(params => {  
      // Do Something with the params you receive
      let id = params.get('id');
    }
}

this.route.params 返回一个你可以订阅的 Observable。

亲切的问候

【讨论】:

  • 对不起,我混淆了 ParamMap 和 params。我更新了我的答案。亲切的问候
猜你喜欢
  • 2018-05-18
  • 2021-06-30
  • 2018-04-07
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 2018-11-28
  • 2021-06-21
相关资源
最近更新 更多