如何使用 Angular 中的快照或 ActivatedRoute 订阅者从 URL 获取 ID?
How to get id from the URL using snapshot or ActivatedRoute subscriber in Angular?
我正在使用快照方法获取值,但它在“类”之后获取值,在本例中为 20,但我需要 33 路径,如获取
credits/33/classes/20 only 20 or credits/33/classes/ only null("")
更新:
我找到了问题的解决方案。
现在可以正常获取id了。错误是在正确的子组件中访问元素,在快照版本中的子 MatDialog 组件中不起作用。
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
console.log(parseInt(this.route.snapshot.paramMap.get('id1')));
If your url has 2 Id values, you can use snapshot of route.parent
console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}
你在路由模块中的路径将是
const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];
假设 id1 是 33 并且
id2 是 20
代码将是:
使用 ActivatedRoute 而不是 ActivatedRouteSnapshot
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id1 = +params['id1'];
this.id2 = +params['id2'];
console.log(id1 + '' + id2);
}
);
}
}
创建一个路由,其中将路由到您的组件,并将其添加到您的模块。
const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: MyComponent },
{ path: 'credits/:id1', component: MyComponent }];
然后,您可以使用 ActivatedRoute
获取您的参数。
export class MyComponent implements {
id1: string;
id2: string;
constructor(private route: ActivatedRoute) {
this.id1 = this.route.snapshot.params['id1'];
this.id2 = this.route.snapshot.params['id2'];
}
}
我正在使用快照方法获取值,但它在“类”之后获取值,在本例中为 20,但我需要 33 路径,如获取
credits/33/classes/20 only 20 or credits/33/classes/ only null("")
更新: 我找到了问题的解决方案。
现在可以正常获取id了。错误是在正确的子组件中访问元素,在快照版本中的子 MatDialog 组件中不起作用。
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
console.log(parseInt(this.route.snapshot.paramMap.get('id1')));
If your url has 2 Id values, you can use snapshot of route.parent
console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}
你在路由模块中的路径将是
const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];
假设 id1 是 33 并且 id2 是 20
代码将是: 使用 ActivatedRoute 而不是 ActivatedRouteSnapshot
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id1 = +params['id1'];
this.id2 = +params['id2'];
console.log(id1 + '' + id2);
}
);
}
}
创建一个路由,其中将路由到您的组件,并将其添加到您的模块。
const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: MyComponent },
{ path: 'credits/:id1', component: MyComponent }];
然后,您可以使用 ActivatedRoute
获取您的参数。
export class MyComponent implements {
id1: string;
id2: string;
constructor(private route: ActivatedRoute) {
this.id1 = this.route.snapshot.params['id1'];
this.id2 = this.route.snapshot.params['id2'];
}
}