文档

Angular 客户端 SDK

ModelRiver Angular SDK 提供基于 Observable 的服务封装,与 Angular 的依赖注入和变更检测系统无缝集成。

安装

Bash
npm install @modelriver/client

Angular 服务已包含在标准 @modelriver/client 分发包中。

配置与使用

1. 提供服务

你可以在组件级或模块级提供 ModelRiverService。

TYPESCRIPT
1import { Component } from '@angular/core';
2import { ModelRiverService } from '@modelriver/client/angular';

2. 初始化并连接

在构造函数中调用 init() 设置 baseUrl,再通过你的后端获取 ws_token 并执行 connect()。

面向企业 Angular 应用的特性

类型安全

Angular SDK 使用 TypeScript 编写,并为 AIResponse、WorkflowStep 等载荷提供接口,便于端到端类型约束。

Observable 流

SDK 中所有状态都通过 Observable 暴露,例如 response$、status$、steps$、error$。这使你可以直接在模板里使用 async pipe,或者用 RxJS 进行组合。

全局配置

你可以在 AppModule 或 AppConfig 中初始化一次 ModelRiverService,让多个组件共享配置。

重连

init() 会调用 reconnect():如果刷新页面时有未完成的请求,只要刷新发生在约 5 分钟内,就会自动恢复。网络断开后服务也会自行重连,期间 connectionState$ 会发出 'reconnecting'(SDK 1.8.0+)。对于更长的中断以及 ModelRiver 重启,请在 init() 中传入 getToken,从你的后端获取新令牌。详见 重连。

Angular 中的 SEO 与性能建议

  1. 使用 Angular Universal 做 SSR,保证基础页面可被搜索引擎抓取
  2. 结合 OnPush 策略构建高性能 AI 界面
  3. 为 AI 生成内容页面维护 canonical URL,避免分享结果页时产生重复内容问题

逐 token 流式传输与实时会话

该服务负责跟踪请求的步骤和最终响应。如需逐 token 的文本(以 "stream": true 发送的异步请求,SDK 1.6.0+),请监听客户端的 stream_* 事件;如需实时跟踪整段对话(会话记忆,SDK 1.7.0+),请使用 subscribeToSession。两者都来自核心包,可以与适配器一起使用。详见 Client SDK 中的“逐 token 流式传输”和“实时会话”。

TYPESCRIPT
1import { Component, Input, NgZone, OnDestroy, OnInit, signal } from '@angular/core';
2import { subscribeToSession, type SessionMessage, type SessionSubscription } from '@modelriver/client';
3 
4@Component({ selector: 'app-live-chat', template: '...' })
5export class LiveChatComponent implements OnInit, OnDestroy {
6 @Input() chatId!: string;
7 messages = signal<SessionMessage[]>([]);
8 private subscription?: SessionSubscription;
9 
10 constructor(private zone: NgZone) {}
11 
12 ngOnInit() {
13 this.subscription = subscribeToSession({
14 getSubscription: () => fetch(`/api/chats/${this.chatId}/live`, { method: 'POST' }).then((r) => r.json()),
15 onMessage: (message) => this.zone.run(() => this.messages.update((list) => [...list, message])),
16 });
17 }
18 
19 ngOnDestroy() {
20 this.subscription?.close();
21 }
22}

如需流式 token,同样可以创建一个 ModelRiverClient 并监听 stream_delta(client.on('stream_delta', (chunk, text) => ...))。

下一步