【发布时间】:2023-03-02 21:37:02
【问题描述】:
服务:
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。
这一切都很好,当点击一篇文章时,路由器会正确更新以显示一个 URL,例如http://www.example.com/articles/5,但我很难修改代码以便 URL 改为显示http://www.example.com/articles/shorthand-5。
我可以让路由器拥有正确的 URL,但由于现在我很容易使用静态数字并将该值减去 1 以获得正确的 JSON 对象,所以我不知道如何读取正确的数据(或与此相关的任何数据)使用 :shorthand 参数作为标识符。
【问题讨论】:
标签: json angular typescript angular2-routing