首页 > 解决方案 > 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。请指导我该怎么做...

标签: angularobservablehttpclient

解决方案


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

推荐阅读