2017-04-03 69 views
0

我是角2中的新角色!在路由Angular 2中获取整个数据传递ID

我想点击标题后获取数据。我通过路由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']); 
    }); 
    } 
} 

现在我已经安慰了标题的价值。但是没有定义。 请告诉我我哪里错了?

+0

很多代码。问题是关于什么问题?什么是实际行为?预期的行为是什么? –

+1

如果你没有在你的路由中定义它,你将无法从'ActivatedRoute'获得'title'参数... – n00dl3

回答

0

你只需要在URL {path: 'blog/**:id**'

ID参数,但是你想拿到冠军参数没有参数称号。

let title = params['title']; 

而且这一个this._activatedRoute.snapshot.data['title']);没有标题数据

你可以用 this._activatedRoute.snapshot.paramMap.get( 'ID'),让您的ID;