我想在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 {
... ?
}
}
答案 0 :(得分:0)
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();
}
...
}
答案 1 :(得分:-1)
关于Angular 2 - How to pass URL parameters?,所提供的解决方案不适用于我的原始问题,但Angular Route guards是正确的功能。
通过路线保护,您可以在组件处理前拦截和捕获路线信息。