krithicka sedhu
krithicka sedhu

Reputation: 31

Api call is not happening while calling Http Request using HttpClient in angular 7

I am converting a post API request written in javascript to typescript, but my new code seems to be not running as i do not see any network calls in the debugger. Please find my code snippets below.

javascript (working)

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 (not working)

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));
    };
}

I have tried many things to run the above code but none of them worked for me.

Upvotes: 1

Views: 1240

Answers (1)

Dhruvan Ganesh
Dhruvan Ganesh

Reputation: 1580

Split your code into the following sections. Angular/RxJS is different from vanilla JavaScript. You create Observable http calls which the Subscriber then reads from.

Inject HttpClient into your class -- necessary for http calls to work. (Needs additional dependencies to work. Please refer https://angular.io/guide/http)

constructor(protected http: HttpClient) {}

Function Definition

 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)

  }

Function Call

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

Upvotes: 2

Related Questions