Joc*_*ado 1 parameters router angular
我是Angular的新手.我正在尝试编辑localhost:4200/edit /:id中的项目,但我无法捕获:id param从中获取相应的数字(它应该是类似localhost:4200/edit/7,例如).当我将params.id输出到控制台时,它总是显示"未定义".
我的app.module.ts
...
import { RouterModule} from '@angular/router';
const routes = [
{ path: '', component: NavigateComponent },
{ path: 'field', component: FieldComponent },
{ path: 'book', component: MaterialFullComponent, children: [
{ path: '', redirectTo: '', pathMatch: 'full' },
{ path: ':id_book', component: MaterialFullComponent }
] },
{ path: 'edit', component: MaterialEditComponent, children: [
{ path: '', redirectTo: '', pathMatch: 'full' },
{ path: 'new', component: MaterialEditComponent },
{ path: ':id', component: MaterialEditComponent }
] },
{ path: '**', redirectTo: '/'}
];
@NgModule({
declarations: [
AppComponent,
AppLoginComponent,
NavigateComponent,
MaterialEditComponent,
MaterialFullComponent,
FieldComponent,
MaterialComponent
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
providers: [
MarcService,
BookService,
BookDetailService
],
bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)
我的MaterialEditComponent
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BookService } from '../book.service';
@Component({
selector: 'app-material-edit',
templateUrl: './material-edit.component.html',
styleUrls: ['./material-edit.component.css']
})
export class MaterialEditComponent implements OnInit {
activatedRoute: ActivatedRoute;
bookService: BookService;
selectedBook = { id_book: null,
numero_ejemplares: null,
autor: '',
titulo: '',
editorial: '',
fecha_publicacion: '',
portada: ''
};
constructor(activatedRoute: ActivatedRoute, bookService: BookService) {
this.activatedRoute = activatedRoute;
this.bookService = bookService;
}
ngOnInit() {
this.activatedRoute.params.subscribe(
(params) => {
console.log(params.id);
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
根据官方的Angular指南,params不鼓励使用.相反,建议是使用paramMap:
还有两个较旧的房产.他们的能力低于他们的替代者,气馁,并且可能在未来的Angular版本中被弃用.
params - 一个Observable,包含特定于路由的必需参数和可选参数.请改用paramMap.
queryParams - 包含可用于所有路由的查询参数的Observable.请改用queryParamMap.
要使用paramMap,请ngOnInit使用以下内容替换:
ngOnInit() {
this.activatedRoute.paramMap.subscribe(params => {
console.log(params.get('id'));
});
}
Run Code Online (Sandbox Code Playgroud)
我意识到这不是你问题的直接解决方法,但我很想知道它是否适合你.我会把它写成评论,但这本来很难读.