angular - Angular 服务传递整数 url 参数被调用两次,将参数值附加到 API 调用
问题描述
我在组件中调用服务并从 routetlink 传递参数
我所拥有的是下面
零件
ngOninit(){
let id = parseInt(this.route.snapshot.paramMap.get('id'));// value is 1
this.getProducts(id);
}
getProducts(id: number) {
this.myService.getProducts(id)
.subscribe(val => {
this.value= val;
}
}
在役
url ="..getdetails?id="
getProducts(id: number): Observable<Products> {
this.url = `${this.Url}${id}`
return this.http.get<Products>(this.Url);
}
在这里我使用 url ="..getdetails?id=" 因为我需要在 url 中传递整数。Httpurlparams 方法只能发送字符串值。
这是我在网络上看到两个 xhr 请求的问题
"..getdetails?id=1"
"..getdetails?id=11"
我所期望的只是我参考文档的一个网络调用,并且看到冷的 observable 会调用两次。但在我的情况下,它在第二次请求时附加了错误的 ID。请指导我该怎么做...
解决方案
ngOninit()
被称为两次是一个不同的问题。不同的查询字符串参数是由
this.url = `${this.Url}${id}`
这里发生的是this.url
在第一次调用服务时发生突变。在第二次调用中,使用了这个变异的值this.url
,并将1
其附加到它导致问题。
使用带有let
关键字的块范围。
重现您的问题和解决方案的示例:
let url ="..getdetails?id="
let id = 1;
url = `${url}${id}`;
console.log(url);
url = `${url}${id}`;
console.log(url);
function setUrl(id) {
console.log('Within a function...');
let url = "..getdetails?id="
url = `${url}${id}`;
console.log(url);
}
setUrl(1);
setUrl(1);
见输出:
$ node app.js
..getdetails?id=1
..getdetails?id=11
Within a function...
..getdetails?id=1
Within a function...
..getdetails?id=1
解决方案:
setUrl(url:string, id:number) {
url = `${url}${id}`;
console.log(url);
return url;
}
getProducts(url:string, id: number): Observable<Products> {
return this.http.get<Products>(this.setUrl(url, id));
}
推荐阅读
- javascript - 优化 react-slick carousel,避免创建过多的 DOM 元素
- bash - “cd”在 Ubuntu 的脚本中不起作用
- react-native - 在函数中转换 this
- amadeus - 访问 Amadeus Test API 时出现系统错误(Flight Inspiration Search)
- swift - 设置 UIDatePicker 在 countDownTimer 模式下的最大时间
- python - 将长度不等的列表的列拆分为多列
- rust - 发布时使用最新版本的依赖项是一种好习惯吗?
- android - Android系统如何创建/storage/self/primary目录?
- c - “分段错误(核心转储)”汇编和c链接程序
- scala - 光滑:模型选项[(col1,col2)],因此两者都丢失或都定义了