2017-05-14 46 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> 

説明:選択された物品のIDパラメータ及び成分の内部getArticleDetails関数にそのパラメータを送信する:ArticlesService内部

getAnArticle機能が使用します。 getArticleDetails関数は、そのparamを使用してそのJSONオブジェクトの内容をサブスクライブします。

{"id":"5","createdOn":1494721160,"title":"title 5","details":"details 5","shorthand":"shorthand-5"} 

注これはJSONファイルで5番目のオブジェクトなので、それはキーIDは、私がgetArticleDetails機能で1によって値を引いてる理由である、4であるということ:このオブジェクトは、次のようになります。

記事がクリックされるとルータが正しく更新され、http://www.example.com/articles/5などのURLが表示されますが、実際にはURLをhttp://www.example.com/articles/shorthand-5と表示するようにコードを修正するのが難しくなります。

私はルータに適切なURLを持たせることができますが、今は静的な数値で簡単に作業していて、正しいJSONオブジェクトを取得するためにその値を1ずつ減算しています。データ(またはそれに関する任意のデータ)を、識別子として:略式パラメータを使用して指定します。

答えて

0

私は、とにかく提供された略記に基づいて記事を返すサーバーにエンドポイントを実装する必要があると思います。このようにして、ユーザーがURLを入力すると、ブラウザーに簡略表記が含まれているため、アプリケーションは記事を取得できます。 もちろん、ArticleServiceの別のメソッドで、その新しく作成されたエンドポイントにリクエストを送信する(たとえば、getArticleFromShorthand)

関連する問題