syncfusion-angular-data-manager

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Syncfusion Angular DataManager

Syncfusion Angular DataManager

When to Use This Skill

何时使用本技能

Use this skill when you need to:
  • Bind local JSON arrays to Angular components
  • Connect Angular apps to remote REST, OData, or GraphQL services
  • Implement querying, filtering, sorting, and paging on data
  • Perform CRUD operations (Create, Read, Update, Delete) with data persistence
  • Work offline and sync data when reconnected
  • Transform and filter data using Query class
  • Customize data communication with middleware
  • Cache data to reduce server requests
  • Handle different data source protocols automatically
This is your primary reference for:
  • Any data operation in Syncfusion Angular components
  • Universal data binding across all components
  • Data source configuration and selection
  • Async operations and error handling
  • Performance optimization with caching

当你需要完成以下需求时可使用本技能:
  • 将本地 JSON 数组绑定到 Angular 组件
  • 将 Angular 应用连接到远程 REST、OData 或 GraphQL 服务
  • 实现数据的查询、过滤、排序和分页功能
  • 执行带数据持久化的 CRUD 操作(创建、读取、更新、删除)
  • 离线工作并在重连后同步数据
  • 使用 Query 类转换和过滤数据
  • 通过中间件自定义数据通信逻辑
  • 缓存数据以减少服务器请求
  • 自动适配不同的数据源协议
本技能是以下场景的首选参考:
  • Syncfusion Angular 组件中的任意数据操作
  • 全组件通用的数据绑定方案
  • 数据源配置与选型
  • 异步操作与错误处理
  • 基于缓存的性能优化

Component Overview

组件概述

The DataManager is Syncfusion's universal data management module that acts as a bridge between your Angular application and any data source. It provides:
  • 10 Built-in Adaptors — Support for JSON, OData v3/v4, REST, Web API, Web Methods, GraphQL, and custom sources
  • Query Class — Powerful filtering, sorting, grouping, and paging API
  • CRUD Operations — Insert, update, delete with automatic handling
  • Promise-based Async — Native JavaScript Promise support
  • Middleware Customization — Pre/post request hooks for authentication and transformation
  • Offline Support — Work without server connection, sync when online
  • Caching — Reduce server load and improve performance
  • Type Safety — Full TypeScript definitions

DataManager 是 Syncfusion 的通用数据管理模块,充当 Angular 应用与任意数据源之间的桥梁。它提供以下能力:
  • 10 个内置 Adaptor — 支持 JSON、OData v3/v4、REST、Web API、Web Methods、GraphQL 和自定义数据源
  • Query 类 — 功能强大的过滤、排序、分组和分页 API
  • CRUD 操作 — 自动处理插入、更新、删除逻辑
  • 基于 Promise 的异步能力 — 原生支持 JavaScript Promise
  • 中间件自定义 — 用于身份验证和数据转换的请求前后钩子
  • 离线支持 — 无服务器连接时可正常工作,上线后自动同步
  • 缓存能力 — 降低服务器负载,提升性能
  • 类型安全 — 完整的 TypeScript 类型定义

⚠️ Accepted Security Risk — Third‑Party Data Exposure

⚠️ 可接受安全风险 — 第三方数据暴露

This skill intentionally functions as an integration boundary and interacts with third‑party APIs as part of its core design.
This exposure is an accepted and documented architectural risk.

本技能在设计上天然作为集成边界,核心功能包含与第三方 API 的交互。这种暴露是已被认可且记录在案的架构风险。

Key Concepts & Trigger Keywords

核心概念与触发关键词

ConceptWhen to UseKey Methods
Local Data BindingWorking with in-memory JSON arraysJsonAdaptor, executeLocal
Remote Data BindingCalling API endpoints for dataUrlAdaptor, WebApiAdaptor, executeQuery
Query ConstructionFiltering, sorting, grouping datafrom(), where(), select(), sortBy(), take()
CRUD OperationsManaging records (add, edit, delete)insert(), update(), remove(), saveChanges()
Adaptor SelectionChoosing the right data source type10 adaptors with decision tree
Error HandlingManaging failure scenarios.catch(), try/catch, error status checking
Offline ModeWorking without server connectionoffline property, localStorage
CachingImproving performanceenableCache, cache clearing strategies
MiddlewareCustomizing requests/responsesapplyPreRequestMiddlewares, applyPostMiddlewares
Async PatternsSequential and parallel operationsasync/await, Promise.all(), then/catch

概念使用场景核心方法
本地数据绑定处理内存中的 JSON 数组JsonAdaptor, executeLocal
远程数据绑定调用 API 端点获取数据UrlAdaptor, WebApiAdaptor, executeQuery
查询构造过滤、排序、分组数据from(), where(), select(), sortBy(), take()
CRUD 操作管理记录(新增、编辑、删除)insert(), update(), remove(), saveChanges()
Adaptor 选型选择适配的数据源类型10 个 Adaptor 及决策树
错误处理处理故障场景.catch(), try/catch, 错误状态校验
离线模式无服务器连接时工作offline 属性, localStorage
缓存提升性能enableCache, 缓存清理策略
中间件自定义请求/响应逻辑applyPreRequestMiddlewares, applyPostMiddlewares
异步模式串行和并行操作async/await, Promise.all(), then/catch

Documentation and Navigation Guide

文档与导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
When to read: Starting new DataManager implementation, understanding package setup, learning TypeScript imports, configuring your first DataManager instance
Topics covered:
  • Package installation and dependencies
  • Module imports and TypeScript types
  • Creating DataManager instances
  • Difference between executeLocal and executeQuery
  • Basic query execution patterns

📄 阅读: references/getting-started.md
适用场景: 开启新的 DataManager 实现、了解包安装配置、学习 TypeScript 导入方式、配置你的第一个 DataManager 实例
覆盖主题:
  • 包安装与依赖管理
  • 模块导入与 TypeScript 类型配置
  • 创建 DataManager 实例
  • executeLocal 与 executeQuery 的区别
  • 基础查询执行模式

Data Binding - Local and Remote

数据绑定 - 本地与远程

📄 Read: references/data-binding.md
When to read: Deciding between client-side and server-side processing, implementing local JSON binding, connecting to remote APIs, understanding executeLocal vs executeQuery patterns
Topics covered:
  • Local binding with json property
  • Remote binding with url + adaptor
  • Client-side vs server-side processing
  • Promise-based async patterns
  • Basic error handling

📄 阅读: references/data-binding.md
适用场景: 选择客户端/服务端处理方案、实现本地 JSON 绑定、连接远程 API、了解 executeLocal 与 executeQuery 模式差异
覆盖主题:
  • 基于 json 属性的本地绑定
  • 基于 url + adaptor 的远程绑定
  • 客户端 vs 服务端处理逻辑
  • 基于 Promise 的异步模式
  • 基础错误处理

Querying and Filtering

查询与过滤

📄 Read: references/querying-and-filtering.md
When to read: Building queries, filtering by multiple conditions, sorting results, searching data, pagination, grouping records, advanced predicates
Topics covered:
  • Query class fundamentals
  • from() and select() methods
  • where() with operators and predicates
  • sortBy(), orderBy(), orderByDescending()
  • take(), skip() for pagination
  • search() method
  • Grouping and aggregation

📄 阅读: references/querying-and-filtering.md
适用场景: 构建查询逻辑、多条件过滤、结果排序、数据搜索、分页、记录分组、高级断言
覆盖主题:
  • Query 类基础
  • from() 和 select() 方法
  • 带操作符和断言的 where() 方法
  • sortBy(), orderBy(), orderByDescending()
  • 分页用的 take(), skip() 方法
  • search() 方法
  • 分组与聚合

CRUD Operations

CRUD 操作

📄 Read: references/crud-operations.md
When to read: Adding new records, updating existing data, deleting records, batch operations, CRUD method parameters, persisting changes to server
Topics covered:
  • Insert (add new records)
  • Update (modify existing records)
  • Remove (delete records)
  • keyField in CRUD method parameters
  • saveChanges() for batch operations
  • Error handling and validation

📄 阅读: references/crud-operations.md
适用场景: 新增记录、更新现有数据、删除记录、批量操作、CRUD 方法参数配置、将变更持久化到服务端
覆盖主题:
  • Insert(新增记录)
  • Update(修改现有记录)
  • Remove(删除记录)
  • CRUD 方法参数中的 keyField
  • 批量操作用的 saveChanges()
  • 错误处理与校验

10 Adaptors Guide - Complete Reference

10 个 Adaptor 完整参考指南

📄 Read: references/adaptors-guide.md
When to read: Selecting appropriate data source, understanding adaptor differences, implementing specific adaptor patterns, working with different API types
Topics covered:
  • JsonAdaptor — Local JavaScript arrays, no server calls
  • ODataAdaptor — OData v3 service endpoints
  • ODataV4Adaptor — OData v4 protocol support
  • UrlAdaptor — Generic RESTful API endpoints
  • WebApiAdaptor — ASP.NET Web API integration
  • WebMethodAdaptor — ASP.NET Web Methods
  • RemoteSaveAdaptor — Client-side queries + server-side CRUD
  • GraphQLAdaptor — GraphQL query language support
  • CustomDataAdaptor — Custom request/response handling
  • CustomAdaptor — Extending built-in adaptors
  • Adaptor decision tree
  • Comparison matrix for all 10
  • Code examples for each adaptor

📄 阅读: references/adaptors-guide.md
适用场景: 选择适配的数据源、了解不同 Adaptor 的差异、实现特定 Adaptor 模式、对接不同类型的 API
覆盖主题:
  • JsonAdaptor — 本地 JavaScript 数组,无服务端调用
  • ODataAdaptor — OData v3 服务端点
  • ODataV4Adaptor — 支持 OData v4 协议
  • UrlAdaptor — 通用 RESTful API 端点
  • WebApiAdaptor — ASP.NET Web API 集成
  • WebMethodAdaptor — ASP.NET Web Methods
  • RemoteSaveAdaptor — 客户端查询 + 服务端 CRUD
  • GraphQLAdaptor — 支持 GraphQL 查询语言
  • CustomDataAdaptor — 自定义请求/响应处理
  • CustomAdaptor — 扩展内置 Adaptor
  • Adaptor 选型决策树
  • 10 个 Adaptor 对比矩阵
  • 每个 Adaptor 的代码示例

Middleware Customization

中间件自定义

📄 Read: references/middleware-customization.md
When to read: Adding authentication headers, transforming requests/responses, logging API calls, implementing custom business logic
Topics covered:
  • Pre-request middleware (applyPreRequestMiddlewares)
  • Post-request middleware (applyPostMiddlewares)
  • Custom headers (Authorization, etc.)
  • Authentication patterns (Bearer tokens)
  • Request/response transformation
  • Error handling in middleware

📄 阅读: references/middleware-customization.md
适用场景: 添加身份验证头、转换请求/响应、记录 API 调用日志、实现自定义业务逻辑
覆盖主题:
  • 请求前中间件(applyPreRequestMiddlewares)
  • 请求后中间件(applyPostMiddlewares)
  • 自定义请求头(Authorization 等)
  • 身份验证模式(Bearer 令牌)
  • 请求/响应转换
  • 中间件中的错误处理

Caching and Offline Mode

缓存与离线模式

📄 Read: references/caching-offline-mode.md
When to read: Improving performance with caching, working offline when server unavailable, implementing sync strategies, managing data persistence
Topics covered:
  • Offline property configuration
  • localStorage for data persistence
  • Cache auto-clearing on CRUD
  • Manual cache management
  • Online/offline workflow
  • Sync strategies

📄 阅读: references/caching-offline-mode.md
适用场景: 通过缓存提升性能、服务不可用时离线工作、实现同步策略、管理数据持久化
覆盖主题:
  • 离线属性配置
  • 基于 localStorage 的数据持久化
  • CRUD 操作触发自动缓存清理
  • 手动缓存管理
  • 在线/离线工作流
  • 同步策略

Advanced Features

高级功能

📄 Read: references/advanced-features.md
When to read: Load on demand for large datasets, lazy loading relationships, pagination strategies, deferred operations, async/await patterns, memory management, state persistence
Topics covered:
  • Load on demand pattern
  • Lazy loading with expand()
  • Pagination (client & server-side)
  • Deferred operations with Promises
  • Async/await patterns
  • Promise.all() for parallel operations
  • Error handling with status codes
  • Memory management strategies
  • Type safety with TypeScript
  • State persistence patterns

📄 阅读: references/advanced-features.md
适用场景: 大数据集按需加载、关系数据懒加载、分页策略、延迟操作、async/await 模式、内存管理、状态持久化
覆盖主题:
  • 按需加载模式
  • 基于 expand() 的懒加载
  • 分页(客户端&服务端)
  • 基于 Promise 的延迟操作
  • async/await 模式
  • 并行操作用的 Promise.all()
  • 基于状态码的错误处理
  • 内存管理策略
  • TypeScript 类型安全
  • 状态持久化模式

How-To Recipes

实操教程

📄 Read: references/how-to-recipes.md
When to read: Quick solutions for common scenarios, best practices, troubleshooting, pattern examples
Topics covered:
  • Work in offline mode
  • Send additional parameters
  • Add custom headers
  • Implement authentication
  • Handle errors gracefully
  • Common patterns
  • Performance optimization tips
  • Troubleshooting guides

📄 阅读: references/how-to-recipes.md
适用场景: 常见场景快速解决方案、最佳实践、问题排查、模式示例
覆盖主题:
  • 离线模式工作方案
  • 发送额外参数
  • 添加自定义请求头
  • 实现身份验证
  • 优雅处理错误
  • 通用开发模式
  • 性能优化技巧
  • 问题排查指南

Quick Start Example

快速入门示例

Setup and Basic Data Binding

配置与基础数据绑定

Step 1: Install Package
bash
npm install @syncfusion/ej2-data
Step 2: Create Component
typescript
import { Component, OnInit } from '@angular/core';
import { DataManager, Query, JsonAdaptor, ReturnOption } from '@syncfusion/ej2-data';

@Component({
  selector: 'app-data-demo',
  templateUrl: './data-demo.component.html',
  styleUrls: ['./data-demo.component.css']
})
export class DataDemoComponent implements OnInit {
  public orders: object[];

  ngOnInit(): void {
    // Local data
    const data = [
      { OrderID: 10248, CustomerID: 'VINET', EmployeeID: 5, ShipCity: 'Reims' },
      { OrderID: 10249, CustomerID: 'TOMSP', EmployeeID: 6, ShipCity: 'Münster' },
      { OrderID: 10250, CustomerID: 'HANAR', EmployeeID: 4, ShipCity: 'Rio de Janeiro' }
    ];

    // Create DataManager with local data
    const dataManager = new DataManager({
      json: data,
      adaptor: new JsonAdaptor()
    });

    // Execute query
    this.orders = dataManager.executeLocal(
      new Query().where('EmployeeID', 'equal', 5)
    );
  }
}
Step 3: Display in Template
html
<table>
  <thead>
    <tr>
      <th>Order ID</th>
      <th>Customer ID</th>
      <th>Employee ID</th>
      <th>Ship City</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let order of orders">
      <td>{{ order.OrderID }}</td>
      <td>{{ order.CustomerID }}</td>
      <td>{{ order.EmployeeID }}</td>
      <td>{{ order.ShipCity }}</td>
    </tr>
  </tbody>
</table>

步骤 1:安装依赖包
bash
npm install @syncfusion/ej2-data
步骤 2:创建组件
typescript
import { Component, OnInit } from '@angular/core';
import { DataManager, Query, JsonAdaptor, ReturnOption } from '@syncfusion/ej2-data';

@Component({
  selector: 'app-data-demo',
  templateUrl: './data-demo.component.html',
  styleUrls: ['./data-demo.component.css']
})
export class DataDemoComponent implements OnInit {
  public orders: object[];

  ngOnInit(): void {
    // 本地数据
    const data = [
      { OrderID: 10248, CustomerID: 'VINET', EmployeeID: 5, ShipCity: 'Reims' },
      { OrderID: 10249, CustomerID: 'TOMSP', EmployeeID: 6, ShipCity: 'Münster' },
      { OrderID: 10250, CustomerID: 'HANAR', EmployeeID: 4, ShipCity: 'Rio de Janeiro' }
    ];

    // 基于本地数据创建 DataManager
    const dataManager = new DataManager({
      json: data,
      adaptor: new JsonAdaptor()
    });

    // 执行查询
    this.orders = dataManager.executeLocal(
      new Query().where('EmployeeID', 'equal', 5)
    );
  }
}
步骤 3:在模板中展示数据
html
<table>
  <thead>
    <tr>
      <th>Order ID</th>
      <th>Customer ID</th>
      <th>Employee ID</th>
      <th>Ship City</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let order of orders">
      <td>{{ order.OrderID }}</td>
      <td>{{ order.CustomerID }}</td>
      <td>{{ order.EmployeeID }}</td>
      <td>{{ order.ShipCity }}</td>
    </tr>
  </tbody>
</table>

Common Patterns

通用开发模式

Remote Server with Promise

基于 Promise 的远程服务对接

typescript
const dataManager = new DataManager({
  url: 'url',
  adaptor: new WebApiAdaptor()
});

// Using Promise
dataManager.executeQuery(new Query().take(10))
  .then((result: ReturnOption) => {
    this.orders = result.result;
  })
  .catch((error) => {
    console.error('Failed to fetch orders:', error);
  });
typescript
const dataManager = new DataManager({
  url: 'url',
  adaptor: new WebApiAdaptor()
});

// 使用 Promise
dataManager.executeQuery(new Query().take(10))
  .then((result: ReturnOption) => {
    this.orders = result.result;
  })
  .catch((error) => {
    console.error('Failed to fetch orders:', error);
  });

Async/Await Pattern

Async/Await 模式

typescript
async fetchOrders(): Promise<void> {
  try {
    const result = await this.dataManager.executeQuery(
      new Query().take(10)
    );
    this.orders = result.result;
  } catch (error) {
    console.error('Error:', error);
  }
}
typescript
async fetchOrders(): Promise<void> {
  try {
    const result = await this.dataManager.executeQuery(
      new Query().take(10)
    );
    this.orders = result.result;
  } catch (error) {
    console.error('Error:', error);
  }
}

Filtering with Predicates

基于断言的过滤

typescript
const query = new Query()
  .where('EmployeeID', 'equal', 5)
  .where('ShipCity', 'startswith', 'Rio');

const result = dataManager.executeLocal(query);
typescript
const query = new Query()
  .where('EmployeeID', 'equal', 5)
  .where('ShipCity', 'startswith', 'Rio');

const result = dataManager.executeLocal(query);

Server-side Operations

服务端操作

typescript
const query = new Query()
  .select(['OrderID', 'CustomerID', 'EmployeeID'])
  .where('EmployeeID', 'greaterThan', 3)
  .sortBy('OrderID')
  .take(10)
  .skip(0);

dataManager.executeQuery(query).then((result: ReturnOption) => {
  this.orders = result.result;
  this.totalRecords = result.count;
});

typescript
const query = new Query()
  .select(['OrderID', 'CustomerID', 'EmployeeID'])
  .where('EmployeeID', 'greaterThan', 3)
  .sortBy('OrderID')
  .take(10)
  .skip(0);

dataManager.executeQuery(query).then((result: ReturnOption) => {
  this.orders = result.result;
  this.totalRecords = result.count;
});

Key Properties Reference

核心属性参考

PropertyTypePurpose
json
array
Local data array
url
string
Remote service endpoint
adaptor
Adaptor
Data source type handler
headers
object[]
Custom HTTP headers
offline
boolean
Enable offline mode
enableCache
boolean
Enable response caching
crossDomain
boolean
Enable cross-domain requests
cachingPageSize
number
Paging record count
timeTillExpiration
number
Cache TTL in milliseconds (default: infinite)
ignoreOnPersist
string[]
Properties to exclude from persistence
timeZoneHandling
boolean
Enable timezone offset handling

属性类型用途
json
array
本地数据数组
url
string
远程服务端点
adaptor
Adaptor
数据源类型处理器
headers
object[]
自定义 HTTP 请求头
offline
boolean
开启离线模式
enableCache
boolean
开启响应缓存
crossDomain
boolean
开启跨域请求
cachingPageSize
number
分页记录数
timeTillExpiration
number
缓存 TTL(单位毫秒,默认永不过期)
ignoreOnPersist
string[]
持久化时要排除的属性
timeZoneHandling
boolean
开启时区偏移处理

Error Handling Best Practices

错误处理最佳实践

typescript
dataManager.executeQuery(query)
  .then((result: ReturnOption) => {
    if (result.result) {
      this.items = result.result;
    }
  })
  .catch((error: any) => {
    if (error.status === 401) {
      // Redirect to login
      console.error('Unauthorized');
    } else if (error.status === 403) {
      // Access denied
      console.error('Forbidden');
    } else if (error.status === 500) {
      // Server error
      console.error('Server error');
    } else if (error.status === 0) {
      // Network error
      console.error('Network error - check connectivity');
    }
  });

typescript
dataManager.executeQuery(query)
  .then((result: ReturnOption) => {
    if (result.result) {
      this.items = result.result;
    }
  })
  .catch((error: any) => {
    if (error.status === 401) {
      // 跳转登录页
      console.error('Unauthorized');
    } else if (error.status === 403) {
      // 访问被拒绝
      console.error('Forbidden');
    } else if (error.status === 500) {
      // 服务端错误
      console.error('Server error');
    } else if (error.status === 0) {
      // 网络错误
      console.error('Network error - check connectivity');
    }
  });

Common Use Cases

常见使用场景

Use Case 1: Display Data Table

场景 1:展示数据表

Start with getting-started.mddata-binding.mdquerying-and-filtering.md
getting-started.md 开始 → data-binding.mdquerying-and-filtering.md

Use Case 2: Implement CRUD Form

场景 2:实现 CRUD 表单

Start with adaptors-guide.mdcrud-operations.mdadvanced-features.md
adaptors-guide.md 开始 → crud-operations.mdadvanced-features.md

Use Case 3: Work with Multiple Data Sources

场景 3:对接多数据源

Start with adaptors-guide.md (decision tree) → specific adaptor pattern → middleware-customization.md
adaptors-guide.md(选型决策树)开始 → 对应 Adaptor 模式 → middleware-customization.md

Use Case 4: Optimize Large Datasets

场景 4:大数据集性能优化

Start with advanced-features.mdcaching-offline-mode.mdhow-to-recipes.md

advanced-features.md 开始 → caching-offline-mode.mdhow-to-recipes.md

TypeScript Type Safety

TypeScript 类型安全

typescript
// Define your data model
interface Order {
  OrderID: number;
  CustomerID: string;
  EmployeeID: number;
  ShipCity: string;
}

// Use generics for type safety
const dataManager: DataManager<Order> = new DataManager({
  json: orders,
  adaptor: new JsonAdaptor()
});

// Typed results
const result = await dataManager.executeQuery(new Query());
const typedOrders: Order[] = result.result as Order[];

typescript
// 定义数据模型
interface Order {
  OrderID: number;
  CustomerID: string;
  EmployeeID: number;
  ShipCity: string;
}

// 使用泛型保证类型安全
const dataManager: DataManager<Order> = new DataManager({
  json: orders,
  adaptor: new JsonAdaptor()
});

// 类型化返回结果
const result = await dataManager.executeQuery(new Query());
const typedOrders: Order[] = result.result as Order[];

Performance Optimization Tips

性能优化技巧

  1. Use proper adaptor — Select adaptor matching your backend
  2. Filter early — Push filtering to server when possible
  3. Enable caching — Reduce redundant server calls
  4. Lazy load — Load data on demand for large datasets
  5. Pagination — Limit records per request
  6. Offline mode — Load once, work offline
  7. Select columns — Fetch only needed fields

  1. 选择合适的 Adaptor — 选择与后端匹配的 Adaptor
  2. 尽早过滤 — 尽可能将过滤逻辑放到服务端执行
  3. 开启缓存 — 减少重复的服务端请求
  4. 懒加载 — 大数据集按需加载数据
  5. 分页 — 限制单次请求的记录数
  6. 离线模式 — 一次加载,离线工作
  7. 字段裁剪 — 仅请求需要的字段