· 7 years ago · Sep 21, 2018, 04:26 PM
1import {HttpClient, HttpHeaders} from '@angular/common/http';
2import {Injectable} from '@angular/core';
3import {Http, Headers, RequestOptions } from '@angular/http';
4
5/*
6 Generated class for the ApiProvider provider.
7
8 See https://angular.io/guide/dependency-injection for more info on providers
9 and Angular DI.
10*/
11@Injectable()
12export class ApiProvider {
13
14 res: {};
15
16 apiUrl: string = 'http://rest-api.local/';
17
18 token: any = {};
19
20 constructor(public http: HttpClient) {
21 }
22
23 execute() {
24 this.getToken();
25 if (this.token) {
26 this.getProducts();
27 }
28 }
29
30 getToken() {
31 const httpOptions = {
32 headers: new HttpHeaders({
33 'Content-Type': 'application/x-www-form-urlencoded',
34 'Access-Control-Allow-Origin' : '*',
35 })
36 };
37 let data = "client_id=1&client_secret=3XXOlWcFbHi5ANakSM5E9fb45yA0Ig75tw4JFaa9&grant_type=client_credentials&scope=*";
38
39 this.res = this.http.post(this.apiUrl + 'oauth/token',
40 data
41 , httpOptions);
42 this.res.subscribe(data => {
43 console.log(data);
44 this.token = data.access_token;
45 });
46
47 }
48}