首页 > 解决方案 > 与 Http 相比,HttpClient 不适用于 Angular 的后端查询

问题描述

好的,我会解释我的问题。我从 Angular 开始,这是我第一次做 REST API,所以有些东西可以逃避我。

在我的例子中,我使用了一个 Period 对象 inTypescript和 in C#,它们是:

期间 TS:

export class Period {
    id: number;
    year: string;
    month: string;
    blocked: boolean;

    constructor(id: number, year: string, month: string, blocked: boolean) {
        this.id = id;
        this.year = year;
        this.month = month;
        this.blocked = blocked;
    }
}

期间 C#:

public class Period
  {
    [JsonProperty(PropertyName = "id")]
    public int ID { get; set; }
    [JsonProperty(PropertyName = "year")]
    public string Year { get; set; }
    [JsonProperty(PropertyName = "month")]
    public string Month { get; set; }
    [JsonProperty(PropertyName = "blocked")]
    public bool Blocked { get; set; }

    public Period() { }
  }

在那之前,我设法通过 Postman 从我的数据库中恢复数据。

邮递员:获取->https://localhost:5001/api/period/GetAllPeriods

[
  {
     "id": 122,
     "year": "2019",
     "month": "03",
     "blocked": false
  },
  {
     "id": 121,
     "year": "2019",
     "month": "02",
     "blocked": false
  }, ...
]

在此处输入图像描述

我做了一些研究和几个测试,下面的代码有效。我检索了JSON我转换为 Period 对象列表的数据Typescript。然后,我将它们显示在我的页面上,一切正常。

但是在Angular 文档中,它Http已经过时并且使用起来更好HttpClient

period.service.ts:http

export class PeriodService {

  constructor(private http: Http) { }

  //Http
  getPeriods(): Observable<Period[]> {
    return this.http.get('/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError),
        map(response => {
          const periods = response.json();
          return periods.map((period) => new Period(period.id, period.year, period.month, period.blocked));
        })
      );
  }

  private handleError(error: HttpErrorResponse) {
    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}`);
      console.error(error);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

所以我尝试使用HttpClient. 但是,我无法在我的服务中恢复数据。

period.service.ts: HttpClient

export class PeriodService {

  constructor(private http: HttpClient) { }

  //HttpClient
  getPeriods(): Observable<Period[]> {
    return this.http.get<Period[]>('https://localhost:5001/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    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}`);
      console.error(error);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };
}

在此处输入图像描述

更清楚地说,我JSON从 API 获取数据,但是当我使用该HttpClient服务时,浏览器控制台中会出现一条错误消息,因为它无法找到尚未访问的数据。所以,我认为我的问题来自服务HttpClient

如果你有想法我很感兴趣。先感谢您。

标签: c#angulartypescripthttpangular-httpclient

解决方案


在您的组件中,当您调用 getPeriods() 方法时,请在其中添加一个订阅,因为它返回一个可观察的类型。

this.getPeriods().subscribe(Response => { console.log(Response)});


推荐阅读