我正在尝试从父路由中检索子路由(称为“id”和“type”),但它未定义。
包含子级CERTS_ROUTES(app.routing.ts)的父路由:
import { Routes, RouterModule } from '@angular/router';
import { CERTS_ROUTES } from './certs/certs.routes';
import { CertsComponent } from './certs/certs.component';
import { LoginComponent } from './login/login.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/certs', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'certs', component: CertsComponent, children: CERTS_ROUTES },
{ path: '**', component: PageNotFoundComponent }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
儿童路线(certs.routes.ts):
import { Routes } from '@angular/router';
import { CertsComponent } from './certs.component';
import { CertDifficultyComponent } from './cert-difficulty/cert-difficulty.component';
import { CertTitleComponent } from './cert-title/cert-title.component';
export const CERTS_ROUTES: Routes = [
{ path: '', component: CertTitleComponent },
{ path: ':id', component: CertTitleComponent },
{ path: ':type', component: CertTitleComponent },
{ path: ':id/:type', component: CertTitleComponent }
];
我正在使用下面的代码来获取“id”或“type”但它返回undefined。
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Rx';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-cert-item',
templateUrl: './cert-item.component.html'
})
export class CertItemComponent implements OnInit {
private subscription: Subscription;
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.subscription = this.route.params.subscribe(
(params: any) => {
let myId = params['id'];
let myType = params['type'];
console.log("ID: ", myId);
console.log("Type: ", myType);
}
);
}
}
如果我检索firstChild
我可以找回正确的“id”,但“type”的值与“id”相同。
我使用的代码(代码段):
ngOnInit() {
this.subscription = this.route.firstChild.params.subscribe(
(params) => {
this.catId = params['id'];
this.diffType = params['type'];
console.log("Id: ", this.catId);
console.log("Type: ", this.catId);
}
);
}
使用this.route.children["0"].url.value[0].path
我可以找回正确的“id”值,并this.route.children["0"].url.value[1].path
获取正确的“type”值。
我通过挖掘控制台中的this.route.children
找到了这个,但它看起来不对,肯定有更好/更优雅的方式?
答案 0 :(得分:1)
你做的一切都正确,期待记录:)
console.log("Id: ", this.catId);
console.log("Type: ", this.catId);
更改为:
console.log("Id: ", this.catId);
console.log("Type: ", this.diffType);
答案 1 :(得分:0)
尝试使用ActivatedRoute.snapshot从您的网址中提取ID和类型参数。如果您遇到路由参数和查询参数,它将处理它们。