2017-12-28 8 views
1

パラメータを使用してルートでデータを取得したいとします。 HTMLでの呼び出しは、このようなものです:角度 - パラメータ化されたルートに基づいて動的URLからデータを取得する

<a routerLink="my-component/2017">2017</a> 

コンポーネントは、主に次のようになります。

export class MyComponent implements OnInit, OnDestroy { 
    year: string; 
    destination: any[]; 

    constructor(private _route: ActivatedRoute, 
       private _info: MyService) {} 

    ngOnInit() { 
    const urlBase = 'http://...'; 
    this.subsUrl = this._route.paramMap.subscribe(
        params => { this.year = params.get('year'); }); 

    this._info.url = urlBase + this.year; 
    this.subsTree = this._info.getJsonData() 
           .subscribe(resultArray => this.destination = resultArray, 
             error => alert(error)); 
    } 

    ngOnDestroy() { 
    this.subsTree.unsubscribe(); 
    this.subsUrl.unsubscribe(); 
    } 

とサービス:

@Injectable() 
export class MyService { 
    url: string; 

    constructor(private _http: HttpClient) { } 

    getJsonData() { 
    return this._http 
     .get(this.url) 
     .catch(this.handleError); 
    } 
} 

サービスは、単一のパラメータに対して正しくデータを返します。 (年)。私の問題は、年を変更すると、手動でページを更新するまで、データは変更されないということです。

+0

私はドキュメントを読ん示唆し、代わりのparamsに 'subscribe'の、' switchMap'を使用して、そこにhttpsをフェッチすべてのデータの操作を行います:/を/angular.io/guide/router – Ric

答えて

0

あなたがthis._route.paramMapとあなたのコンポーネント名を使用していると私はあなたが更新することをお勧めMyComponent であるあなたのURLを構築するためにrouterLinkとqueryParamsを使用することができますrouterLink

<a [routerLink]="['/my']" [queryParams]="{year:'2017'}">2017</a> 
0

次のように。

<a [routerLink]="['/my-component']" [queryParams]="{year:2017}"> 
    2017 
</a> 

最終URLは次のようになります。

http://localhost:3000/my-component?year=2017 
関連する問題