As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserService.ts:
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { serializeNodes } from '@angular/compiler/src/i18n/digest';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UserService {
baseurl = "http://127.0.0.1:8000";
httpHeaders = new HttpHeaders({'Content-Type':'application/json'});
constructor(private http: HttpClient) { }
login(username, password): Observable<any>{
return this.http.post<{token: string}>(this.baseurl + '/api/v1/rest-auth/login/', {username, password}).pipe(
tap(
res => {
localStorage.setItem('token', JSON.stringify(res.token));
}))
}
// Other methods of UserService follow...
Concerns were raised regarding the getToken function within UserService where the error encountered was SyntaxError due to an unexpected token. The relevant code snippets are shown below:
// Code snippet from UserService.ts
getToken(){
return localStorage.getItem('token');
}
The next segment of code is related to JwtService.ts:
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class JwtService implements HttpInterceptor{
constructor(private injector: Injector) { }
intercept(req, next){
let serv = this.injector.get(UserService)
let tokenizedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${serv.getToken()}`
}
})
return next.handle(tokenizedReq)
}
}
Login.component.ts contains the logic for handling user login and token retrieval:
// Code snippet from Login.component.ts
login(){
this.api.login(this.username, this.password).subscribe(
response => {
this.token = response;
console.log(response);
alert(response)
this.router.navigate(['/student'])
console.log(this.api.loggedIn)
},
error =>{
console.log("An error occurred");
console.log(error)
}
);
}
The final piece of the puzzle lies within app.modules.ts:
// Code snippet from app.modules.ts
// Necessary imports and declarations
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
NavigationComponent,
LoginComponent,
StudentComponent,
DeanComponent,
AdminComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
In conclusion, despite efforts to troubleshoot the issues, such as using JSON.parse method in getToken, the problem persists with the 'object Object' result upon executing alert in login.component.ts.