Service:
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));
}
}
Component:
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;
});
}
}
Router:
{ path: 'articles/:id', component: PArticlesComponent }
HTML:
(navigation)
<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>
(article)
<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>
Explanation:
The getAnArticle function inside the ArticlesService uses the :id parameter of a selected article and sends that parameter to the getArticleDetails function inside of the component. The getArticleDetails function then uses that param to subscribe the contents of that JSON object. This object looks like this:
{"id":"5","createdOn":1494721160,"title":"title 5","details":"details 5","shorthand":"shorthand-5"}
Note that this is the 5th object in the JSON file, so it's key id is 4, which is why I'm subtracting the value by 1 in the getArticleDetails function.
This all works great, and when an article is clicked the router updates properly to show a URL such as http://www.example.com/articles/5 but I'm having a real hard time modifying the code so that the URL instead displays http://www.example.com/articles/shorthand-5.
I can get the router to have proper URL's but since right now I'm easily working with a static number and subtracting that value by 1 to get the correct JSON object, I can't figure out how to read the correct data (or any data for that matter) by using the :shorthand parameter as the identifier.