Angularjs 尝试使用url中的凭据优化我的HttpClient调用
我必须用这种方式打电话Angularjs 尝试使用url中的凭据优化我的HttpClient调用,angularjs,Angularjs,我必须用这种方式打电话 https://username:password@my.domain.com/api 在ajax中,我做了类似的事情 $.ajax({ url: endPoint, type: 'POST', async: false, contentType: "application/json; charset=utf-8", dataType: "json",
https://username:password@my.domain.com/api
在ajax中,我做了类似的事情
$.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");
}
});
如果不做这样的事情,我怎么能对新Angular的HttpClient做同样的事情呢
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
}
它可以工作,但是这个字符串连接很难看。
我不是这类技术的专家,我希望能得到一些帮助,我不知道你为什么要这么做,但无论如何 我要做的是在服务中创建一个函数,其中包含多个变量(用户、域等) 调用该函数时,它将返回完整的URL 这看起来像这样:
user: string;
password: string;
domain: string;
endpoint: string;
get url() { return `https://${this.user}:${this.password}@${this.domain}/${this.endpoint}`; }
您只需设置变量值,在任何http调用中,您只需
let url = this.myService.url;
在我的项目中,我的问题不是关于代码设计,而是关于HttpClient组件及其获取干净URL和凭据的能力HttpClient用于进行http调用。为此,您需要给它一个URL。所以你需要建立这个URL。所以我会说不。但是,你可以使用拦截器,在打电话之前重建你的URL。是你问的吗?因为否则,我不知道如何帮助你…我发布Ajax查询就是因为这个,真正的问题是“我是否尽了我所能打一个好电话”?Ajax方法非常流畅,这就是使用高级抽象框架所能得到的!AJAX可能很灵活,但Angular的HttpClient更易于使用。那么,拦截器对您来说是一个好的选择吗?不,它在不应该是逻辑的地方添加了逻辑。我应该处理具体的案件,我认为不是这样的