2017-05-14 2 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 객체의 내용을 구독합니다. 이 JSON 파일에서 5 개체입니다

{"id":"5","createdOn":1494721160,"title":"title 5","details":"details 5","shorthand":"shorthand-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을 입력하면 브라우저에 속기가 포함되어 응용 프로그램에서 기사를 검색 할 수 있습니다. 그리고 당연히, ArticlesService의 또 다른 메소드는 새로 생성 된 끝점 (예 : getArticleFromShorthand)에 요청을 보냅니다.