Angular 4路由参数捕获为未定义

时间:2017-08-27 17:03:59

标签: angular parameters router

我是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]
})

我的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);
      }
    );
  }
}

2 个答案:

答案 0 :(得分:7)

据官方Angular guide称,不鼓励使用params。相反,建议是使用paramMap代替:

  

仍有两个较旧的属性。他们的能力低于他们的替代者,气馁,并且可能在未来的Angular版本中被弃用。

     

params - 一个Observable,包含特定于路径的必需参数和可选参数。改为使用paramMap。

     

queryParams - 包含可用于所有路由的查询参数的Observable。请改用queryParamMap。

要使用paramMap,请将ngOnInit替换为以下内容:

ngOnInit() {
  this.activatedRoute.paramMap.subscribe(params => {
    console.log(params.get('id'));
  });
}

我意识到这不是您问题的直接解决方法,但我很想知道它是否适合您。我会把它写成评论,但它很难读。

答案 1 :(得分:2)

弄错了,或者至少让它运转起来。

将路由定义更改为:

const routes = [
  { path: '', component: NavigateComponent },
  { path: 'field', component: FieldComponent },
  { path: 'book/:id_book', component: MaterialEditComponent },
  { path: 'edit/:id', component: MaterialEditComponent },
  { path: '**', redirectTo: '/'}
];

显然,使用“儿童”并不好。