服务:
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函数使用该param来订阅该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之类的网址,但我很难修改代码,以便显示网址{ {3}}。
我可以让路由器拥有正确的网址,但是现在我可以轻松使用静态数字并将该值减去1以获得正确的JSON对象,我无法做到通过使用:shorthand参数作为标识符,弄清楚如何读取正确的数据(或任何数据)。
答案 0 :(得分:0)
我认为你必须在服务器中实现一个端点,无论如何都会根据提供的速记返回文章。这样,当用户在浏览器中输入url包含速记时,您的应用程序就可以检索该文章。 当然,在ArticlesService中另一个向新创建的端点发送请求的方法(例如getArticleFromShorthand)