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

How can i retrieve a status code in Angular?

我是 Angular 的新手,为了练习,我想制作一个小应用程序,用户可以首先使用他的用户名登录。为此,如果后端 returns http 状态为 200,我想存储已登录的用户。但我无法获取请求的 http 状态。我已经在这里和其他网站上查找了几个 post,但所有这些解决方案似乎都不适合我。

我的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 的回答和这个 post 我能够解决这个问题。实际上我之前尝试设置 observe:'response' 但我没有将其放入 httpOptions 而是放入 HttpHeaders ,但没有用。 我的工作 post 请求现在看起来像这样:

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;
  }

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

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

HttpClient 允许您通过将 {observe: 'response'} 添加到您的请求选项来查看完整的响应,而不仅仅是 body。这将 return 具有 body、headers、状态、url 等的 HttpResponse object

所以 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);
});