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

时间:2020-07-01 07:20:55

标签: angular httpresponse

我是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; } 。 我的工作职位要求现在看起来像这样:

# Define data base credential ----
psql <- DBI::dbDriver("PostgreSQL")

con <- dbConnect(
  psql,
  dbname = 'mydbname',
  host = 'hostname',
  port = 5444,
  user = 'username',
  password = 'password') 

2 个答案:

答案 0 :(得分:1)

通过在请求选项中添加{observe: 'response'},HttpClient允许您查看完整的响应,而不仅仅是正文。这将返回具有正文,标头,状态,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);
});

答案 1 :(得分:-1)

不要将响应转换为JSON,那么您可以在此处找到它

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