Angular - 根据参数化路径从动态URL中检索数据

时间:2017-12-28 11:12:28

标签: angular angular4-router

我想通过路径获取带参数的数据。在html中,调用是这样的:

<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);
  }
}

服务正确返回单个参数(年份)的数据。我的问题是,如果我更改年份数据不会改变,直到我手动刷新页面。

2 个答案:

答案 0 :(得分:0)

当您使用this._route.paramMap时,您的组件名称为MyComponent 我建议您更新routerLink,如下所示

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

答案 1 :(得分:0)

您可以使用queryParams与routerLink构建网址。

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

最终的网址是:

http://localhost:3000/my-component?year=2017