Hi. I wanted to share the code, how to connect to Cuba-Platform REST Api with OAuth2 in Angular 2 and Ionic 2 TypeScript.
So here it comes:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class AuthService {
ourcode;
accesstoken;
tokentype;
expires_in;
scope;
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
getAccessToken() {
let client_id = 'client';
let client_secret= 'secret';
var basicheader = btoa(client_id + ':' + client_secret);
var headers = new Headers();
headers.append('authorization', 'Basic '+ basicheader);
headers.append('cache-control', 'no-cache');
headers.append('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
var tokendata = 'grant_type=password&username=admin&password=admin';
this.http.post('http://localhost:8080/app/rest/v2/oauth/token', tokendata, {headers: headers}).subscribe((data) => {
this.accesstoken = data.json().access_token;
this.tokentype = data.json().token_type;
this.expires_in = data.json().expires_in;
this.scope = data.json().scope;
console.log(this.accesstoken + " " + this.tokentype + " - " + this.expires_in + " - " + this.scope );
//this.router.navigate(['/books']);
})
}
}
Create a service in Angular2 (ng generate service AuthService) or provider in Ionic 2 (ionic generate provider AuthService).
Copy and paste the code from here and into the service file.