2017-04-03 81 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;