如何解决Angular获取查询参数和呼叫服务
我的角度应用程序出现问题。我必须打电话给服务,从URL中读取一些参数。它不起作用,因为在完成具有参数的订阅之前已触发服务。在我的服务文件中,有以下内容:
constructor(private http: HttpClient,private route: ActivatedRoute) {
this.route.queryParams.subscribe(params => {
this.param1 = params['param1'];
this.param2 = params['param2'];
});
}
然后是服务:
getConfigs() {
let configPath = baseUrl + this.param1 + "/" + this.param2;
return this.http.get<any>(configPath);
}
因此,在我的AppComponent
中,我调用了getConfigs()
服务,但由于两个参数未定义,所以该服务不起作用。我该如何解决?这就是我在AppComponent
this.service.getConfigs().subscribe((configData) => {
this.configParams = configData;
});
解决方法
您可以使用switchMap
之类的RxJS高阶映射运算符来链接相互依赖的可观察对象。尝试以下
array
尽管我会说最好在组件而不是服务中获取路由参数。因此,您可以执行以下操作
服务
constructor(private http: HttpClient,private route: ActivatedRoute) { }
getConfigs() {
return this.route.queryParams.pipe(
switchMap(params => {
let configPath = baseUrl + params['param1'] + "/" + params['param2'];
return this.http.get<any>(configPath);
})
);
}
组件
constructor(private http: HttpClient) { }
getConfigs(param1: any,param2: any) {
const configPath = baseUrl + param1 + '/' + param2;
return this.http.get<any>(configPath);
}
,
从路由器获取查询参数,然后使用first()
运算符仅获取第一个事件,然后使用switchMap()
来获取带params选项的数据。
constructor(
private _http: HttpClient,private _route: ActivatedRoute,) { }
getConfigs() {
return this._route.queryParams.pipe(
// rxjs operator skip empty object
filter(params => !!Object.keys(params).length),// rxjs operator use only first event
first(),// rxjs operator switch to another observable
switchMap(params => this._http.get('host',{ params })),);
}
,
您需要将值传递给服务。
this.service.getConfigs(this.param1,this.param2).subscribe((configData) => {
this.configParams = configData;
});
getConfigs(param1,param2) {
let configPath = baseUrl + param1 + "/" + param2;
return this.http.get<any>(configPath);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。