I'm relatively new to Angular5/TypeScript, so I apologize for the (maybe) trivial question.
I'm trying to implement an authentication service which I intend to use in order to let my Angular5 frontend, consume some REST API exposed by a wordpress backend.
So far the service is implemented and working. What I'm missing, right now is a way to inject login data into REST requests.
To be more precise, I know how to do that but I don't now how to access the login information that I've previously stored in my shared service.
But let me be even more specific and let me share my code:
// auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { JwtHelperService } from '@auth0/angular-jwt';
interface IUser
{
token: string,
token_expires: number,
user_display_name: string,
}
@Injectable()
export class AuthService
{
private currentUser: IUser = null;
private nonce: string = '';
constructor(
private http: HttpClient,
private jwt: JwtHelperService,
)
{
// set User Info if saved in local/session storage
.
.
.
}
logIn(username: string, password: string, persist: boolean): Observable<boolean>
{
return this.http.post(
API_BASE_DOMAIN + API_BASE_PATH + '/jwt-auth/v1/token',
{ username: username, password: password },
{
observe: 'response', // Full response instead of the body only
withCredentials: true, // Send cookies
}
).map(response => {
this.nonce = response.headers.get('X-WP-Nonce');
const body: any = response.body
// login successful if there's a jwt token in the response
if (body.token)
{
// set current user data
this.currentUser = <IUser>body;
// store username and jwt token in local storage to keep user logged in between page refreshes
let storage = (persist) ? localStorage : sessionStorage;
storage.setItem('currentUser', JSON.stringify(this.currentUser));
// return true to indicate successful login
return true;
}
else
{
// return false to indicate failed login
return false;
}
});
}
getNonce(): string
{
console.log((this.nonce) ? this.nonce : '');
return (this.nonce) ? this.nonce : '';
}
getToken(): string
{
console.log((this.currentUser) ? this.currentUser.token : '');
return (this.currentUser) ? this.currentUser.token : '';
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AuthService } from './main/auth/services/auth.service';
import { AuthGuardService } from './main/auth/services/auth-guard.service';
import { API_BASE_DOMAIN } from './main/auth/services/auth.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NonceHttpInterceptor } from './main/auth/auth.interceptor';
const appRoutes: Routes = [
.
.
.
];
@NgModule({
declarations: [
AppComponent
],
imports : [
BrowserModule,
HttpClientModule,
RouterModule.forRoot(appRoutes),
// Jwt Token Injection
JwtModule.forRoot({
config: {
tokenGetter: (***AuthService?????***).getToken,
whitelistedDomains: [ API_BASE_DOMAIN ]
}
})
],
providers : [
AuthService,
AuthGuardService,
{
provide: HTTP_INTERCEPTORS,
useClass: NonceHttpInterceptor,
multi: true
}
],
bootstrap : [
AppComponent
]
})
export class AppModule
{
}
As you can see in my code at //JWT Token Injection, I need to specify a token getter which is implemented in my auth.service.
In a component file I can access its public methods by injecting the service as a parameter for the constructor, like this:
//login.component.ts
import { AuthService } from '../services/auth.service';
@Component({
.
.
.
})
export class MyLoginComponent implements OnInit
{
constructor(
private authService: AuthService,
)
{
.
.
.
}
onFormSubmit()
{
this.authService.logIn(uname, pwd, persist)
.subscribe(
.
.
.
);
}
}
But I don't seem to find a way to access a service method at module level!
I know, I could use static access for my tokenGetter and move everything at class level instead of instance level (like this: AuthService.getToken
) but I think there is a better, more elegant way to access the getToken()
method.
Thank you in advance for any hint/help.