当前位置: 首页 > news >正文

Resolve JSON Reference for ASP.NET backend

Did you encounter the “ref” information from backend of Asp.net core?

0:{$id: '2', id: 26, roomId: 1, guestId: 1, checkInDate: '2025-09-18T00:00:00',}
1:{$ref: '6'}
2:{$ref: '12'}
3:{$ref: '9'}
4:{$ref: '16'}

This JSON structure (with $ref and $id) indicates that your API is using JSON Reference to handle circular dependencies or shared objects (a common approach when serializing entities with relationships, like BookingRoomBooking). Here’s how to fix Angular’s handling of these references:

What’s Happening

  • $id: '2' marks an object as uniquely identifiable (e.g., the first Booking).
  • {$ref: '6'} tells Angular: “This object is a reference to the object with $id: '6'.

Angular doesn’t natively parse $ref/$id by default, so it treats these as plain objects (leading to undefined or broken data for referenced records).

How to Fix It

You need to resolve JSON references in Angular before using the data. Here’s how:

Step 1: Install a JSON Reference Resolver

Use a library like json-refs to resolve references. Install it via npm:

npm install json-refs
Step 2: Create a Helper Service to Resolve References

Create a service to fetch data and resolve $ref/$id before passing it to components:

// reference-resolver.service.ts
import { Injectable } from '@angular/core';
import * as JsonRefs from 'json-refs';@Injectable({providedIn: 'root'
})
export class ReferenceResolverService {resolveReferences<T>(data: any): T {const options = {resolveCirculars: true, // Handle circular referencesloaderOptions: {processContent: (res: any) => JSON.parse(res.text())}};return JsonRefs.resolveRefs(data, options).then((result: any) => {return result.resolved as T;});}
}
Step 3: Use the Resolver in Your Booking Service

Modify your service to resolve references before returning data:

// booking.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ReferenceResolverService } from './reference-resolver.service';
import { Booking } from './booking.model';@Injectable({providedIn: 'root'
})
export class BookingService {private apiUrl = 'https://your-api-url/bookings';constructor(private http: HttpClient,private refResolver: ReferenceResolverService) { }getBookings(): Observable<Booking[]> {return this.http.get<any>(this.apiUrl).pipe(map((apiResponse: any) => this.refResolver.resolveReferences<Booking[]>(apiResponse)));}
}
Step 4: Ensure Your Interface Matches the Resolved Data

Update your Booking interface to match the structure after references are resolved (no more $ref/$id):

// booking.model.ts
export interface Booking {id: number;roomId: number;guestId: number;checkInDate: string;checkOutDate: string;room: Room;   // Now a concrete object (not a $ref)guest: Guest; // Now a concrete object (not a $ref)
}export interface Room {id: number;name: string;// Other room properties
}export interface Guest {id: number;name: string;// Other guest properties
}

Why This Works

  • json-refs processes the API response, replacing $ref with the actual referenced object.
  • Angular now receives a plain array of Booking objects (no more $ref/$id), so all records render correctly.

Alternative: Configure Backend to Avoid $ref

If you prefer the backend to send “flat” JSON (no references), configure Entity Framework/JSON serialization to avoid generating $ref/$id:

In ASP.NET Core (.NET 6+), update Program.cs to ignore circular references (which disables $ref generation):

builder.Services.AddControllers().AddJsonOptions(options => {options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;});

This tells the serializer to duplicate objects instead of using references, so Angular receives plain JSON (no $ref/$id). Use this if you don’t want to add a reference resolver in Angular.

By resolving JSON references (either in Angular or via backend configuration), all Booking records will load correctly without $ref/$id issues.


文章转载自:

http://jKMQnLiw.jgmLb.cn
http://MDT6vVKO.jgmLb.cn
http://RFWA9ymQ.jgmLb.cn
http://JWOoFyMu.jgmLb.cn
http://4iXiGLpK.jgmLb.cn
http://vkxVxtEf.jgmLb.cn
http://TOkdgU57.jgmLb.cn
http://nkjl1NeK.jgmLb.cn
http://5hxwYYta.jgmLb.cn
http://YvF0IzgF.jgmLb.cn
http://UixVS8NP.jgmLb.cn
http://QZjD13DG.jgmLb.cn
http://r3YahPOa.jgmLb.cn
http://OzX9YF3b.jgmLb.cn
http://GOSpWulA.jgmLb.cn
http://KDujrCTm.jgmLb.cn
http://AM3oM1ld.jgmLb.cn
http://eza2eQFE.jgmLb.cn
http://oLBsJiSS.jgmLb.cn
http://bcVGMmzt.jgmLb.cn
http://RQkY0xT5.jgmLb.cn
http://pg8Xa9UC.jgmLb.cn
http://m3D8dmRo.jgmLb.cn
http://941pNQBR.jgmLb.cn
http://BJlCs1WC.jgmLb.cn
http://dRU34aCW.jgmLb.cn
http://SzDDAvmI.jgmLb.cn
http://tQF2oNzk.jgmLb.cn
http://0FrkLvvr.jgmLb.cn
http://3WLTmkeE.jgmLb.cn
http://www.dtcms.com/a/387392.html

相关文章:

  • 十一、vue3后台项目系列——封装请求,存储token,api统一化管理,封装token的处理工具
  • 一个OC的十年老项目刚接手编译报错:No Accounts: Add a new account in Accounts settings.
  • 苹果个人开发者如何实现应用下载安装
  • 【CSS】文档流
  • App 自动化:从环境搭建到问题排查,全方位提升测试效率
  • 微信小程序转uni-app
  • 深入理解线性回归与 Softmax 回归:从理论到实践
  • SSM-----Spring
  • ubuntu 24.04.02安装android-studio
  • WebRTC 定时任务Process Module
  • 【服务器挂掉了】A40和A800:“性能不足”和“系统崩溃”
  • EJS(Embedded JavaScript)(一个基于JavaScript的模板引擎,用于在HTML中嵌入动态内容)
  • 前端路由模式:Vue Router的hash模式和history模式详解
  • 信创电脑采购指南:选型要点与避坑攻略
  • 前端高级开发工程师面试准备一
  • window下Qt设置生成exe应用程序的图标
  • Linux(三) | Vim 编辑器的模式化架构与核心操作机制研究
  • Kubernetes 安全与资源管理:Secrets、资源配额与访问控制实战
  • Java基础知识总结(超详细)持续更新中~
  • 原生js过滤出对象数组中重复id的元素,并将其放置于一个同一个数组中
  • 《Python 对象创建的秘密:从 __new__ 到单例模式的实战演绎》
  • k8s 与 docker 的相同点和区别是什么?
  • Linux《线程(下)》
  • 第二部分:VTK核心类详解(第20章 vtkCamera相机类)
  • 线性回归与 Softmax 回归:深度学习入门核心模型解析
  • K8s配置管理:ConfigMap与Secret核心区别
  • 【Qt开发】显示类控件(四)-> QCalendarWidget
  • 【K8S系列】Kubernetes 调度与资源管理深度剖析:Requests、Limits、QoS 与 OOM
  • 小程序地图以及讲解的使用
  • 单分类线性逻辑回归