我想通过路由获取参数数据。在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);
}
}
该服务正确返回单个参数(年份)的数据。我的问题是,如果我更改年份数据不会更改,直到我手动刷新页面。
你可以使用queryParams
和routerLink来构建网址。
<a [routerLink]="['/my-component']" [queryParams]="{year:2017}">
2017
</a>
最终的URL将是:
http://localhost:3000/my-component?year=2017
当您使用this._route.paramMap
并且您的组件名称是MyComponent
我建议您更新您的routerLink
如下
<a [routerLink]="['/my']" [queryParams]="{year:'2017'}">2017</a>