[英]Fetching whole data passing id in route Angular 2
我是角度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']);
});
}
}
現在,我已經安慰了title的值。 但是是不確定的。 請告訴我我要去哪里錯了?
您在url {path: 'blog/**:id**'
只有id參數
但是您嘗試獲取標題參數,沒有參數標題。
let title = params['title'];
也是這個this._activatedRoute.snapshot.data['title']);
沒有標題數據
您可以使用this._activatedRoute.snapshot.paramMap.get('id');獲得您的ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.