首页 文章

在Angular(2)bootstrapped组件中读取URL(矩阵||查询)参数

提问于
浏览
2

我想在Angular引导的组件中读取可选的URL参数,无论是查询还是矩阵参数,这是/在ngOnInit()中 .

据我所知,“ActivatedRoute”在未在插座中加载的组件中不可用,因此使用index.html如:

<body>
  <app-root>Loading...</app-root>
</body>

和app.module.ts文件包含:

bootstrap: [AppComponent]

是否以及如何从http://localhost:4200/my-component/id;param1=abc访问参数?

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
  styles: []
})
export class AppComponent implements OnInit {

  constructor(private router: Router) {
    ... ?
  }

  ngOnInit(): void {
    ... ?
  }
}

2 回答

  • -1
    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Router, ActivatedRoute, Params } from '@angular/router';
    import { Subscription } from 'rxjs/Subscription';
    
    export class AppComponent implements OnInit, OnDestroy {
      private var1: string;
      private var2: string;
      private sub: Subscription;
    
      constructor(
        private route: ActivatedRoute,
        private router: Router
      ) {}
    
      ngOnInit() {
        // assign the subscription to a variable so we can unsubscribe to prevent memory leaks
        this.sub = this.route.queryParams.subscribe((params: Params) => {
          this.var1 = params['var1'];
          this.var2 = params['var2'];
        });
    
        console.log(this.var1, this.var2);
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    ...
    }
    
  • 0

    关于Angular 2 - How to pass URL parameters?,提供的解决方案不适用于我的原始问题,但是Angular Route guards是正确的功能 .

    通过路径保护,您可以在组件处理前拦截和捕获路径信息 .

相关问题