c# - 与 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
。
如果你有想法我很感兴趣。先感谢您。
解决方案
在您的组件中,当您调用 getPeriods() 方法时,请在其中添加一个订阅,因为它返回一个可观察的类型。
this.getPeriods().subscribe(Response => { console.log(Response)});
推荐阅读
- javascript - 在js中动态创建字段
- haskell - 将列表拆分为 Haskell 中的列表列表
- javascript - 基于覆盖层更改传单地图上的图例
- spring-boot - 无法使用 IntelliJ Idea 社区调试/停止 springboot 应用程序
- azure-devops - Azure 管道表达式在模板中不起作用
- javascript - Highcharts:如何在用户点击的位置显示注释?
- node.js - ZKSync 不是构造函数
- firebase - Google Firestore 是缓存文档和集合还是总是请求新的?
- javascript - 当用户可以任意添加或删除输入标签时如何从输入标签中获取值
- python - 我试图在python中计算两个datetime之间的时间间隔,但结果不正确