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

问题描述 投票:1回答:2

我想通过路由获取参数数据。在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);
  }
}

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

angular angular4-router
2个回答
0
投票

你可以使用queryParams和routerLink来构建网址。

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

最终的URL将是:

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

0
投票

当您使用this._route.paramMap并且您的组件名称是MyComponent我建议您更新您的routerLink如下

<a [routerLink]="['/my']" [queryParams]="{year:'2017'}">2017</a>
© www.soinside.com 2019 - 2024. All rights reserved.