4

I have to make calls with this format

https://username:[email protected]/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 thing with the new Angular's HttpClient 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'm not a specialist of this kind of technology, I would appreciate some help

1 Answer 1

2

I don't know why you would do that but anyways.

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

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

This would 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 need to do is set your variable values, and in any http call, all you need to do is

let url = this.myService.url;
Sign up to request clarification or add additional context in comments.

5 Comments

in my project it almost looked like that, my question is not about code design but about the HttpClient component and its ability to get clean urls and credentials
HttpClient is used to make http calls. For that, you need to give it an URL. So you need to build this URL. So I would say no. But, you could use an Interceptor, to rebuild your URL just before making your call. Is it what you asked ? Because otherwise, I have no idea how to help you ...
I posted the Ajax query just because of this, the real question is "am I doing all I can do for making a good call"? The Ajax approach was smoother
That's what you get with high level abstraction frameworks ! AJAX might be flexible, but Angular's HttpClient is simpler to use. So, is the Interceptor a good alternative for you ?
No, it adds logic where should not be logic. I should handle specific cases and I think it's not..the case :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.