2017-05-14 175 views
2

服務:角2路由映射經由JSON

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文件中的第五對象,所以它的密鑰ID號爲4,這就是爲什麼我被1中getArticleDetails功能減去值。

這一切都很好,當點擊一篇文章時,路由器會正確更新以顯示一個URL,例如http://www.example.com/articles/5,但我很難修改代碼,以便URL顯示http://www.example.com/articles/shorthand-5

我可以讓路由器擁有正確的URL,但由於現在我很容易使用靜態數字並將該值減1以獲得正確的JSON對象,我無法弄清楚如何讀取正確的數據(或關於該事項的任何數據),通過使用:簡寫參數作爲標識符。

回答

0

我認爲你必須在服務器中實現一個端點,它將基於提供的速記返回文章。當用戶輸入url時,這種方式包含瀏覽器中的簡寫,您的應用程序可以檢索文章。 當然,ArticlesService中的另一種方法將請求發送到新創建的端點(例如getArticleFromShorthand)