Я создаю метод регистрации и входа. Я использую перехватчик, но это ошибка 401. Я не получаю токен для установки заголовка.
Это мой код: https://stackblitz.com/github/ntgiang4991/jwt
Токен файла .interceptor.ts:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
let token = localStorage.getItem('token');
request = this.addToken(request, token)
return next.handle(request);
}
private addToken(request: HttpRequest<any>, token: string){
return request.clone({
setHeaders: {
'Authorization': `Token ${token}`,
'Content-type': 'application/json; charset=utf-8'
},
})
}
Файл auth.service.ts
constructor(
private http: HttpClient,
private jwt: JwtService
) { }
login(email: string, password: string) {
return this.http.post('https://conduit.productionready.io/api/users/login', { email, password });
}
register(username: string, email: string, password: string) {
return this.http.post<{ token: string }>('https://conduit.productionready.io/api/users', { username, email, password }).pipe(tap(res => {
this.login(email, password)
}))
}
logout() {
localStorage.removeItem('token');
}
public get loggedIn(): boolean {
return localStorage.getItem('token') !== null;
}
Файл register.component. html
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card rounded-0 mt-5">
<div class="card-header">
<h3 class="mb-0">Register</h3>
</div>
<div class="card-body">
<form action="" class="form">
<div class="form-group">
<label for="username">Username</label>
<input [(ngModel)]="registerUserData.username" name="username" type="text" required class="form-control rounded-0">
</div>
<div class="form-group">
<label for="email">Email</label>
<input [(ngModel)]="registerUserData.email" name="email" type="text" required class="form-control rounded-0">
</div>
<div class="form-group">
<label for="password">Password</label>
<input [(ngModel)]="registerUserData.password" name="password" type="password" required class="form-control rounded-0">
</div>
<button (click)="registerUser()" type="button" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
</div>
Файл register.component .ts
registerUser() {
console.log(this.registerUserData.username, this.registerUserData.email, this.registerUserData.password);
this._auth.register(this.registerUserData.username, this.registerUserData.email, this.registerUserData.password).subscribe(
res => console.log(res),
err => console.log(err)
);
}