Как правильно отправить пост-запрос с помощью Http-клиента в Angular
Я хочу создать страницу регистрации, которая будет содержать email, имя пользователя, имя, фамилию и пароль. Я использую Angular 13 в качестве front-end и Django в качестве back-end. Формы работают идеально, но я получаю ошибку в консоли.
- here is my registration form:
[![введите описание изображения здесь][1]][1]
- here is the error on the console:
- here is the list of services I wrote: 1. code for auth.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ResearcherData } from './../models/researcher-data.interface';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { HandleError, HttpErrorHandler } from './http-error-handler.service';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'my-auth-token'
})
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
private url = 'http://127.0.0.1:2000/auth/users/';
private handleError: HandleError;
constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler,
) {
this.handleError = httpErrorHandler.createHandleError('AuthService');
}
/** register researcher to the server */
register(researcherdata: ResearcherData): Observable<ResearcherData>{
return this.http.post<ResearcherData>(this.url, researcherdata,httpOptions)
.pipe(
catchError(this.handleError('register', researcherdata))
)}
}
- code for http-error-handler.service.ts
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { MessageService } from './message.service';
/** Type of the handleError function returned by HttpErrorHandler.createHandleError */
export type HandleError =
<T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;
/** Handles HttpClient errors */
@Injectable({
providedIn: 'root'
})
export class HttpErrorHandler {
constructor(private messageService: MessageService) { }
/** Create curried handleError function that already knows the service name */
createHandleError = (serviceName = '') =>
<T>(operation = 'operation', result = {} as T) =>
this.handleError(serviceName, operation, result);
/**
* Returns a function that handles Http operation failures.
* This error handler lets the app continue to run as if no error occurred.
*
* @param serviceName = name of the data service that attempted the operation
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
handleError<T>(serviceName = '', operation = 'operation', result = {} as T) {
return (error: HttpErrorResponse): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
const message = (error.error instanceof ErrorEvent) ?
error.error.message :
`server returned code ${error.status} with body "${error.error}"`;
// TODO: better job of transforming error for user consumption
this.messageService.add(`${serviceName}: ${operation} failed: ${message}`);
// Let the app keep running by returning a safe result.
return of( result );
};
}
}
- code for message.service.ts:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); } clear() { this.messages = []; } }
- вот код для researcher-data.interface.ts: `` export interface ResearcherData{
email: "",
username: "",
first_name: "",
last_name: "",
password: ""
}
```
- here is code for researcher-signup.component.ts:
import { AuthService } from './../../../core/services/auth.service'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms' @Component({ selector: 'researcher-signup', templateUrl: './researcher-signup.component.html', styleUrls: ['./researcher-signup.component.css'] }) export class ResearcherSignupComponent implements OnInit { forms: FormGroup; constructor( private fb: FormBuilder, private authService: AuthService ) { } ngOnInit(): void { this.forms = this.fb.group({ email: ['', [Validators.required, Validators.email]], username: ['', [Validators.required]], first_name: ['', [Validators.required, Validators.maxLength]], last_name: ['', [Validators.required]], password: ['', [Validators.required, Validators.maxLength]], }); } get email() { return this.forms.get('email'); } get password() { return this.forms. get('password'); } get username() { return this.forms.get('username'); } get first_name() { return this.forms.get('first_name'); } get last_name() { return this.forms.get('last_name'); } onSubmit() { // console.log(this.forms.value,this.forms.valid); this.authService.register(this.forms.value) .subscribe(result => console.log(result)) } }
- here is Django Rest page on http://localhost:2000/auth/users/ :
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/izKZb.jpg