저는 Angular를 처음 사용하고 연습을 위해 사용자가 처음에는 사용자 이름으로 만 로그인 할 수있는 작은 응용 프로그램을 만들고 싶습니다. 그렇게하기 위해 백엔드가 http 상태 200을 반환하는 경우 로그인 한 사용자를 저장하고 싶습니다. 그러나 요청의 http 상태를 가져올 수 없습니다. 나는 이미 여기와 다른 사이트에서 여러 게시물을 찾았지만 이러한 모든 솔루션이 나를 위해 작동하지 않는 것 같습니다.
내 Angular 버전 : 8.2.14
내 로그인 서비스는 다음과 같습니다.
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { User } from '../model/User';
@Injectable({
providedIn: 'root',
})
export class LoginService {
constructor(private http: HttpClient) {}
loginUrl = 'login';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
login(user: User) {
const request = this.http
.post(this.loginUrl, user, this.httpOptions)
.pipe(catchError(this.handleError));
return request;
}
private handleError(error: HttpErrorResponse) {
console.log('handleError Method');
console.log('Errorcode', error.status);
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
}
}
그리고 이것은 서비스를 호출하는 로그인 구성 요소입니다.
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { LoginService } from 'src/app/services/login.service';
import { User } from '../../../model/User';
@Component({
selector: 'app-login-component',
templateUrl: './login-component.component.html',
styleUrls: ['./login-component.component.css'],
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
user: User;
// loginService: LoginService;
constructor(private loginService: LoginService) {}
ngOnInit() {}
login(username: string, password: string) {
const dummyUser = { username, password };
this.loginService.login(dummyUser).subscribe((data) => {
console.log('data', data);
this.user = data;
console.log('user', this.user);
});
}
}
편집 :
Mari Mbiru의 답변과이 게시물 https://stackoverflow.com/a/47761516/12360845 로이 질문을 해결할 수있었습니다. 실제로 세트에 시도 observe:'response'
하기 전에하지만 난에 넣어하지 않았다 httpOptions
있지만에서 HttpHeaders
작동하지 않았다. 내 작업 게시물 요청은 이제 다음과 같습니다.
login(user: User) {
const request = this.http
.post<User>(
`${this.loginUrl}`,
{ username: user.username, password: user.password },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response',
}
)
.pipe(catchError(this.handleError));
return request;
}
HttpClient를 사용하면 {observe: 'response'}
요청 옵션 에 추가하여 본문 대신 전체 응답을 볼 수 있습니다. 그러면 본문, 헤더, 상태, URL 등이있는 HttpResponse 개체가 반환됩니다.
따라서 httpOptions는 다음과 같아야합니다.
httpOptions = {
observe:'response'
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
그리고 구독 :
this.loginService.login(dummyUser).subscribe((res) => {
console.log('response', res);
this.user = res.body;
console.log('user', this.user);
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다