Trying to optimize my Angular HttpClient call with credentials in url

I need to make calls with this format

https://username:password@my.domain.com/api

in ajax I did something like this

$.ajax({
          url: endPoint,
          type: 'POST',
          async: false,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          username: myUsername,
          password: myPassword,
          beforeSend: function (xhr) {
               xhr.withCredentials = true;
               xhr.setRequestHeader("Accept", "application/json; odata=verbose");
          }
    });

how can i do the same with the new w500> without doing something like this?

let url = baseProtocol + username + ":" + password + "@" + baseUrl

this.http.post(url,{
  headers: {
    "Accept": "application/json;odata=verbose",
    "Content-Type": "application/json;odata=verbose",
  }
}).subscribe( res => {
    //do stuff
  }, err => {
    //do other bad related stuff
  }

it works, but this string concatenation is ugly. I am not a specialist in this kind of technology, I would appreciate help

+4
source share
1 answer

I don’t know why you will do it, but anyway.

What would I do is either make a function in the service, with several variables (user, domain, etc.).

When you call a function, it returns the full URL.

It will look like this:

user: string;
password: string;
domain: string;
endpoint: string;

get url() { return `https://${this.user}:${this.password}@${this.domain}/${this.endpoint}`; }

All you have to do is set the values ​​of the variables, and in any HTTP call all you have to do is

let url = this.myService.url;
+2
source

Source: https://habr.com/ru/post/1690767/


All Articles