How do I connect ASP.Net web api to Angular without this ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

How do I connect ASP.Net web api to Angular without this ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

决定弄清楚 Angular 到底是怎么回事。获得了一个使用 JSON 文件的演示应用程序(使用 angular Cli 中的 db.json 和 json 服务器)。一切正常。

所以我开始冒险并决定构建一个 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 });

在我的 angular 应用中,我有

//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

我在这里阅读了很多关于此错误的文章,但似乎都没有处理这种情况,(none 我无论如何都能找到)并且我检查了一些

我错过了什么?

这是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
        }
      ]
    }

这个错误只是因为你试图循环一个对象。只需将数据带入

这样的结果
this.getTasks().subscribe(result => {
  this.data = result.tasks;
})

获取数据中的响应后,您可以使用循环。

根据您的JSON,HttpGet 预计会收到如下数据模型:

export interface TaskResponse {
  tasks: Task[];
}

并用 .pipe(map) 到 return 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));
}

Sample Demo on StackBlitz