Angular url plus sign converting to space

后端 未结 7 1574
梦如初夏
梦如初夏 2020-11-29 06:02

I have angular application where i want to pass plus sign + in query string like:

http://localhost:3000/page?name=xyz+manwal
7条回答
  •  迷失自我
    2020-11-29 06:54

    In Angular v6.1.10, if you just need to fix the "+" sign encoding in one spot, this is what worked for me.

    getPerson(data: Person) {
    
      const httpParams = new HttpParams({
        fromObject: {
          id: data.id,
          name: data.name,
          other: "xyz+manwal"
        }
      });
    
      // manually encode all "+" characters from the person details
      let url = BASE_URL + "/select?" + httpParams.toString().replace(/\+/gi, '%2B');
    
      return this.http.get(url);
    }
    

    I found if you try to replace the "+" signs when initializing the httpParams object it doesn't work. You have to do the replacement after converting httpParams to a string, as shown on this line:

    let url = BASE_URL + "/select?" + httpParams.toString().replace(/\+/gi, '%2B');
    

提交回复
热议问题