Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular中检索状态代码?_Angular_Httpresponse - Fatal编程技术网

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

如何在Angular中检索状态代码?,angular,httpresponse,Angular,Httpresponse,我是Angular的新手,为了练习,我想制作一个小应用程序,在这个应用程序中,用户只需使用自己的用户名即可登录。为此,如果后端返回http状态200,我想存储登录的用户。但是我无法获取请求的http状态。我已经在这里和其他网站上查阅了一些帖子,但所有这些解决方案似乎都不适合我 我的角度版本是:8.2.14 这是我的登录服务: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, Ht

我是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的回答和这篇文章,我能够解决这个问题。实际上,我以前试过设置
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;
  }
登录(用户:用户){
const request=this.http
.邮政(
`${this.loginUrl}`,
{用户名:user.username,密码:user.password},
{
headers:newhttpheaders({'Content-Type':'application/json'}),
观察:'回应',
}
)
.pipe(catchError(this.handleError));
返回请求;
}

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


订阅((res)=>res['status'],(err)=>

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


订阅((res)=>res['status'],(err)=>

通过向请求选项添加
{observe:'response'}
,HttpClient允许您查看完整响应,而不仅仅是正文。这将返回一个HttpResponse对象,该对象具有主体、标题、状态、url等

因此,http选项应该是:

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

HttpClient允许您通过向请求选项添加
{observe:'response'}
来查看完整响应,而不仅仅是正文。这将返回一个HttpResponse对象,该对象具有主体、标题、状态、url等

因此,http选项应该是:

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

这回答了你的问题吗?请始终尝试缩小示例代码。这是否回答了您的问题?请始终尝试缩小示例代码。