I am trying to include a private API key in a service, by bringing it in from a private endpoint on the server. I am just not sure how to go about placing this into the service it's required in.
To be honest, I'm a little lost as to how to do this. This is my service below. The private API key is for a onesignal account which pushes mobile notifications to mobile devices.
EDITED QUESTION:
I've altered the code a little now and have made use of another service called KeysService. This then creates the response which allows me to define the this.authKey value - which is a string, as this is what I need.
As you will notice, the getKey() method is now being called in on the constructor and the console.log of this.authKeys is printing the relevant string I need to place into the Authorization Header found on the sendNotification() method below it.
import { Injectable } from '@angular/core';
import { OneSignal } from './onesignal';
import { environment } from '../environments/environments';
import { HttpClient, HttpHeaders, HttpBackend } from '@angular/common/http';
import { throwError } from 'rxjs';
import { KeysService } from './keys.service';
@Injectable({
providedIn: 'root'
})
export class OnesignalService {
authKey: string;
api_url = environment.one_signal.api_url;
private http: HttpClient;
constructor(handler: HttpBackend, private keysService: KeysService) {
this.http = new HttpClient(handler);
this.getkey();
}
getkey() {
this.keysService.getPrivateKeys()
.subscribe(
authKeys => {
this.authKey = authKeys.data[0].key;
console.log(this.authKey);
}
)
}
sendNotification(pushData: any) {
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json; charset=utf-8",
"Authorization": "PRIVATE_API_KEY"
})
}
return this.http.post<OneSignal>(this.api_url, pushData, httpOptions);
}
handleError(error) {
let errorMessage = '';
if (error.error) {
errorMessage = error.error.message;
} else {
errorMessage = error;
}
return throwError(errorMessage);
}
}
How do I bring in this.authKey into the sendNotification() method, say like (see below):
sendNotification(pushData: any) {
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json; charset=utf-8",
"Authorization": this.authKey
})
}
return this.http.post<OneSignal>(this.api_url, pushData, httpOptions);
}
I think I am close, but I am missing a trick to get this to set.