決定找出所有關于 Angular 的大驚小怪。有一個使用 JSON 檔案的演示應用程式(使用來自 angular Cli 的 db.json 和 jsonserver)。一切都很好。
所以我冒險并決定構建一個 C# API(因為這是一個長期的計劃)。
我立即遇到了 CORS 問題,并在我的 asp.net 配置中解決了 (startup.cs)
app.UseCors( options =>
{
options
.WithOrigins("http://localhost:4200/")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
我像這樣輸出我的 JSON(在我所有的應用程式中都這樣做了一千次)
return Json(new { tasks = _context.Tasks });
在我的角度應用程式中,我有
//private apiUrl = 'http://localhost:5101/tasks'; //<- this is using json server
private apiUrl = "https://localhost:44363/home/tasks"; //<- this is my asp.net api
constructor(private http: HttpClient) {}
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>(this.apiUrl);
}
我的網路服務吐出與 json 服務器完全相同的 json(char for char)但是在我的瀏覽器控制臺中(在處理 cors 問題之后)我得到了這個 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
我在這里閱讀了很多關于此錯誤的文章,但似乎沒有處理這種情況(無論如何我都找不到)并且我檢查了一些
我錯過了什么?
這是json
{
"tasks": [
{
"id": 1,
"text": "Doctors Appointment",
"day": "1st January 2022 at 10:30 AM",
"reminder": false
},
{
"id": 2,
"text": "Meeting",
"day": "5th July 2022 at 11:45 AM",
"reminder": false
},
{
"id": 3,
"text": "Car Servicing",
"day": "15th October 2022 at 8:30 AM",
"reminder": false
},
{
"id": 4,
"text": "Cleaner",
"day": "3rd November 2022 at 10:00 AM",
"reminder": false
},
{
"id": 5,
"text": "Dinner",
"day": "6th July 2022 at 7:50 PM",
"reminder": false
}
]
}
uj5u.com熱心網友回復:
這個錯誤只是因為你試圖回圈一個物件。只需將資料轉化為結果即可
this.getTasks().subscribe(result => {
this.data = result.tasks;
})
在資料中獲取回應后,您可以使用回圈。
uj5u.com熱心網友回復:
根據您的 JSON,HttpGet 期望接收如下資料模型:
export interface TaskResponse {
tasks: Task[];
}
并.pipe(map)回傳response.tasks為Observable<Task[]>.
import { map } from 'rxjs/operators';
getTasks(): Observable<Task[]> {
return this.http
.get<TaskResponse>(this.apiUrl)
.pipe(map((response: TaskResponse) => response.tasks));
}
StackBlitz 上的示例演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397738.html
