如何在 Angular 中检索状态代码?



我是 Angular 的新手,为了练习,我想做一个小应用程序,用户一开始只需使用他的用户名即可登录。为此,如果后端返回http状态200,我想存储登录的用户。但是我无法获得我的请求的 http 状态。我已经在这里和其他网站上查找了几篇帖子,但所有这些解决方案似乎都不适合我。

我的角度版本是: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);
});

不要将响应转换为 JSON,然后你可以在这里找到它

HTTP.post('.....'(.subscribe( (res( => res['status'], (err( =>.....(;

相关内容

  • 没有找到相关文章

最新更新