我使用 Dummy APIs 来演示 Asyn-await 在处理延迟的服务器响应时的重要性。简单的事情是,如果我对这个 URL (https://hub.dummyapis.com/delay?seconds=3) 进行 get 调用,我将收到响应,即“此响应已延迟 3 秒” 3秒。但我的承诺总是被拒绝。这是我的代码:
服务
constructor(private _httpClient: HttpClient) {}
getHeroes(): Observable<any> {
return this._httpClient.get('https://hub.dummyapis.com/delay?seconds=3');
}
组件 TS 文件
error: string = 'Oops! something went wrong';
async ngOnInit() {
try {
let x = await this.fetchData();
// this.heroes = [...x];
} catch (error: any) {
console.log("I've received an error: ", error.message);
}
}
async fetchData(): Promise<any> {
return new Promise((resolve, reject) => {
this._heroListService.getHeroes().subscribe(
(res: any) => {
if (typeof res === 'object') {
resolve(res.text()); // Converting the response in string format
} else {
reject(new Error('Invalid response format')); // Reject if the response is not in the expected format
}
},
(error: any) => {
reject(error); // Reject with the error
},
() => {
console.log('Call complete!');
}
);
});
}
我也检查了我的网络通话。 API 工作正常。状态为“200 OK”并且也有响应:
我还缺少什么。请指出我的代码有什么问题。
我知道回复的格式有问题。它不是 JSON,所以我使用的是:
(res: any) => {
if (typeof res === 'object') {
resolve(res.text()); // Converting the response in string format
} else {
reject(new Error('Invalid response format')); // Reject if the response is not in the expected format
}
}
我应该做的是重构我的服务方法如下:
getHeroes(): Observable<any> {
return this._httpClient.get('https://hub.dummyapis.com/delay?seconds=3',
{responseType: 'text',}); // response type needs to be told first
}