HttpClient 与使用 Angular 的后端查询的 Http 不同

HttpClient does not work as opposed to Http for backend queries with Angular

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

在我的例子中,我在 TypescriptC# 中使用了 Period 对象,它们是:

期间 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 从我的数据库中恢复了数据。

邮递员:GET -> 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 documentation上写着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.');
  };
}

更清楚地说,我从API获取JSON数据,但是当我使用HttpClient服务时,浏览器控制台出现错误信息,因为它不能找到可访问的数据。 所以,我认为我的问题来自 HttpClient.

的服务

如果你有想法我很感兴趣。 提前谢谢你。

好几天我都被这个问题困住了,一旦我的问题被问到,我就找到了解决方案...

我的问题是:import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api';

事实证明,为了开发我的应用程序,我开始使用 HttpClientInMemoryWebApiModule。 但是这个模块与 HttpClient 不兼容。 必须删除它才能使用 HttpClient.

现在我的应用程序可以正常工作并显示数据。

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

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