目前我在pram id中显示我的单个博客,但我需要在url中显示当前查看博客标题: http://localhost:4200/blogs/viewsingleblog/1 以 http://localhost:4200/blogs/viewsingleblog/Exclusive-T-shirt-For-You
博客json数据是:
blogs = [
{
id: 2,
title: 'Exclusive T-shirt For You ..!',
discription:"Lorem ipsum ......",
postDate: '02-05-2017',
author: 'admin',
thambnils: '/src/app/images/t-shirt1.jpg',
public: true,
like: false
}
]
**app route is:**
{
path:'blogs',
children: [
{
path: '', component:BlogComponent
},
{
path: 'viewsingleblog/:title',
component: SingleblogComponent
}
]
}
博客服务
getBlog(title:any):Promise<Blog>{
title= title.replace(new RegExp('-', 'gi'), '+');
// for replace blank space to "-" to show url
const singleBlog= `${this.url}/?${title}`;
console.log("Your Log Url => " + singleBlog);
return this.http.get(singleBlog)
.toPromise()
.then(response => response.json().data as Blog)
.catch(this.handleError)
}
private handleError(error: any): Promise<any>{
console.log(error);
return Promise.reject(error.message || error);
}
我的单个博客组件是:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params , Router } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';
import { Blog } from '../../class/blog';
import { BlogService } from '../../service/blog.service';
@Component({
selector: 'app-singleblog',
templateUrl: './singleblog.component.html',
styleUrls: ['./singleblog.component.css']
})
export class SingleblogComponent implements OnInit {
blog:Blog;
recentBlog:Blog[];
constructor(
private _blogService: BlogService,
private location: Location,
private route:ActivatedRoute,
private router: Router
) { }
getBlog():void {
this.route.params
.switchMap((params: Params) =>
this._blogService.getBlog(this.route.snapshot.params.title))
.subscribe(blog => this.blog = blog);
console.log(this.blog);
}
getRecentBlogs():void {
this._blogService.getBlogs().then(recentBlog=> this.recentBlog = recentBlog);
}
ngOnInit() {
this.getBlog();
this.getRecentBlogs();
}
backnow() { this.location.back(); }
changeBlog(id:number){ this.router.navigate(['/viewsingleblog', id]); }
}
答案 0 :(得分:0)
您需要订阅。
title: string;
private sub: any;
constructor(private route: ActivatedRoute) {...}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.title = params['title'];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}