【问题标题】:Api call is not happening while calling Http Request using HttpClient in angular 7在角度 7 中使用 HttpClient 调用 Http 请求时未发生 Api 调用
【发布时间】:2019-01-22 13:44:41
【问题描述】:

我正在将用javascript 编写的post API 请求转换为typescript,但我的新代码似乎没有运行,因为我在调试器中看不到任何网络调用。请在下面找到我的代码 sn-ps。

javascript(工作中)

private resourcesAccessable(url, token, clientId, resources) {

    var request = new XMLHttpRequest();
    request.open('POST', url, false);
    request.setRequestHeader("Authorization", "Bearer " + token);
   request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    console.log(request);
    var response ;
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            var status = request.status;
            if (status >= 200 && status < 300) {
                response = JSON.parse(request.responseText);
            } else if (status == 403) {
                console.log('Authorization request was denied by the server.');
                return null;
            } else {
                console.log('Could not obtain authorization data from server.');
                return null;
            }
        }
    }
    var params = "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&response_mode=permissions&audience="+clientId;
    if(Array.isArray(resources)){
        for (var i = 0; i < resources.length; i++) {
            params = params+"&permission="+resources[i]
        }
    }
    request.send(params);
    console.log(response);
    return response;
}

typescript(不工作)

resourcesAccessable(url, token, clientId, resources) {
private http: HttpClient,
private payload

const httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + token
    })
};

this.payload = new URLSearchParams();
this.payload.set('grant_type','urn:ietf:params:oauth:grant-type:uma-ticket');
this.payload.set('response_mode','permissions');
this.payload.set('audience', clientId);
this.payload.set('permission',resources);

return this.http.post(url, payload.toString(), httpOptions)
    .pipe(
        tap(
            (data) => {
                console.log('----->>>', data);
            }
        )
    ), error => {
        console.log('error ' + JSON.stringify(error));
    };
}

我尝试了很多方法来运行上面的代码,但没有一个对我有用。

【问题讨论】:

    标签: xmlhttprequest angular7 angular-httpclient


    【解决方案1】:

    将您的代码拆分为以下部分。 Angular/RxJS 与原生 JavaScript 不同。您创建 Observable http 调用,然后订阅者从中读取。

    将 HttpClient 注入到您的类中——http 调用正常工作所必需的。 (需要额外的依赖才能工作。请参考https://angular.io/guide/http

    constructor(protected http: HttpClient) {}
    

    函数定义

     resourcesAccessable(url, token, clientId, resources): Observable<any> {
        const payload = new URLSearchParams()
    
        const httpOptions = {
            headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer ' + token
            })
        }
    
        payload.set('grant_type', 'urn:ietf:params:oauth:grant-type:uma-ticket')
        payload.set('response_mode', 'permissions')
        payload.set('audience', clientId)
        payload.set('permission', resources)
    
        return this.http.post(url, payload.toString(), httpOptions)
    
      }
    

    函数调用

      this.resourcesAccessable('', '', '', '')
            .subscribe(
              (data) => {
                console.log('----->>>', data);
              }
            , error => {
                console.log('error ' + JSON.stringify(error));
            }, 
             () => console.log('Completed'));
    

    【讨论】:

    • 试过了,但是没用。错误 {"body":{"error":"Collection 'realms' not found"},"url":"localhost:8081/auth/realms/enliven/protocol/openid-connect/token","headers":{ "normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found"}
    • 您的状态为 404,这意味着您在 localhost:8081 上的服务器没有提到的路由/api
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多