服务:
export class ArticlesService {
private _url = 'https://example.firebaseio.com/.json';
constructor(private _http: Http) {
}
getAllArticles(): Observable<any> {
return this._http.get(this._url)
.map((response: Response) => response.json())
.catch((error) => Observable.throw(error));
}
getAnArticle(articleId: any): Observable<any> {
return this._http.get(this._url.replace(".json", articleId + ".json"))
.map((response: Response) => response.json())
.catch((error) => Observable.throw(error));
}
}组件:
theArticle = {};
constructor(private _activatedRoute: ActivatedRoute, private _articlesService: ArticlesService, private _router: Router) {
this._router.events
.filter(theEvent => theEvent instanceof NavigationStart)
.subscribe((theEvent: NavigationStart) => {
if (/\/articles\/\d/.test(theEvent.url)) {
const urlDetails = theEvent.url.split('/');
const articleId = urlDetails[urlDetails.length - 1];
this.getArticleDetails(articleId);
console.log(this.theArticle);
}
});
}
ngOnInit() {
this.getArticleDetails(this._activatedRoute.snapshot.params['id']);
}
getArticleDetails(articleId: any) {
if (articleId != null ) {
this._articlesService.getAnArticle(articleId - 1)
.subscribe(data => {
this.theArticle = data;
});
}
}路由器:
{ path: 'articles/:id', component: PArticlesComponent }HTML:
(导航)
<ul class="sidebar-ul" *ngIf="allArticles.length">
<li *ngFor="let anArticle of limit(allArticles)">
<a [routerLink]="['/articles', anArticle.id]">{{anArticle.title}}
<br/>
<span class="date">{{formatDate(anArticle.createdOn)}}</span>
</a>
</li>
</ul>(文章)
<div *ngIf="theArticle.id">
<h2 class="article-title">
<a href="#">{{theArticle.title}}</a>
</h2>
<div class="meta">
<p class="date">{{formatDate(theArticle.createdOn)}}</p>
</div>
<p [innerHTML]="theArticle.details"></p>
</div>解释:
ArticlesService内的getAnArticle函数使用所选文章的:id参数,并将该参数发送到组件内的getArticleDetails函数。然后,getArticleDetails函数使用该参数订阅该JSON对象的内容。此对象如下所示:
{"id":"5","createdOn":1494721160,"title":"title 5","details":"details 5","shorthand":"shorthand-5"}请注意,这是JSON文件中的第5个对象,因此它的键id是4,这就是为什么我在getArticleDetails函数中将该值减去1。
这一切都很好用,当一篇文章被点击时,路由器会正确地更新以显示一个网址,比如http://www.example.com/articles/5,但是我在修改代码时遇到了很大的困难,使得网址显示为http://www.example.com/articles/shorthand-5。
我可以让路由器具有正确的URL,但由于现在我很容易处理静态数字并将该值减去1以获得正确的JSON对象,因此我不知道如何使用:速记参数作为标识符来读取正确的数据(或任何相关数据)。
发布于 2017-05-15 05:45:17
我认为您必须在服务器中实现一个端点,该端点无论如何都会根据提供的速记返回文章。这样,当用户在浏览器中输入包含速记的url时,您的应用程序可以检索文章。当然,还有ArticlesService中向新创建的端点(例如getArticleFromShorthand)发送请求的另一种方法
https://stackoverflow.com/questions/43967729
复制相似问题