1

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.

1 Answer 1

2

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'));
Sign up to request clarification or add additional context in comments.

2 Comments

Tried but it's not working. error {"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"}
You have a status 404, meaning that your server on localhost:8081 does not have the mentioned route/api

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.