获取路径Angular 2中传递id的整个数据

时间:2017-04-03 07:48:36

标签: javascript angular typescript

我是角度2的新人!

我想在点击标题后获取数据。我在路线中传递id。我正在添加我的路线文件,我的组件文件和我的html文件。

**路线:**

  const routes : Routes = [
  {path: '' , redirectTo : '/blog' , pathMatch : 'full'},
  {path: 'blog' , component: BlogsComponent},
  {path: 'blog/:id', component: BlogDetailComponent},
  {path: '**', component: PageNotFoundComponent}
];

blogs.component.ts

import { Component, OnInit } from '@angular/core';
import {BlogService} from "../services/blog.service";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {Blog} from "../blog";


@Component({
  selector: 'app-blogs',
  template : `
        <h1>My Blog</h1>
        <ul>
          <li *ngFor="let blog of blogs"
              [class.selected]="blog === selectedHero"
              (click)="onSelect(blog)" [routerLink]="['/blog', blog.id]">
            <h3 class="badge">{{blog.title}} ~ Written By: User-{{blog.userId}}</h3>
          </li>
        </ul>

`
})
export class BlogsComponent implements OnInit {

  public errorMessage: string;
  blogs: Blog[];
  selectedHero: Blog;

  constructor(private _blogService : BlogService, private _router: Router , private _activatedRoute : ActivatedRoute) {}

  onSelect(blog){
    this._router.navigate(['/blog' , blog.id])
  }
  ngOnInit() {
    console.log('I am in BlogsComponent');
    this._blogService.getBlog()
      .subscribe( resBlogData => this.blogs = resBlogData ,
        resBlogError => this.errorMessage = resBlogError
      );
  }
}

博客-detail.component.ts

import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {BlogService} from "../services/blog.service";

@Component({
  // selector: 'app-blog-detail',
  template: `

    <p>
      You Selected Blog with Id = {{blogId}}
    </p>

`
})
export class BlogDetailComponent implements OnInit {
  public blogId;
  public blogTitle;
  public blog;
  constructor( private _activatedRoute: ActivatedRoute , private _blogService : BlogService) { }

  ngOnInit(): void {
    this._activatedRoute.params.subscribe((params: Params)=>{
      let id = parseInt(params['id']);
      let title = params['title'];
      this.blogId = id;
      this.blogTitle = title;
      console.log( 'title : ' + this._activatedRoute.snapshot.data['title']);
    });
  }
}

现在我已经安慰了游戏的价值。但是未定义。 请告诉我哪里出错了?

1 个答案:

答案 0 :(得分:0)

您在网址{path: 'blog/**:id**'

中只有id参数

但是你想获得标题参数,没有参数标题。

let title = params['title'];

另外这个this._activatedRoute.snapshot.data['title']);没有标题数据

你可以得到你的身份证明 this._activatedRoute.snapshot.paramMap.get( 'ID');