midwayjs 自定义组件开发
实际上官方已经明确说明了自定义组件开发的一些技巧了,我主要简单说明i下一些问题
一些问题
- 自定义组件就是一个小的应用
- 如果需要注册controller 注意在index.ts 中对于controller 的export,不然是不能生效的
- 如果是多模块的项目,注意需要构建
- 自定义组件是可以直接使用主应用的配置以及服务的,配置比较好说,核心就是接口定义,会自动注入的
- 对于自定义组件也是可以获取主应用注入的服务的,但是因为没法直接获取类型,解决方法是可以通过ioc 容器的服务名获取服务,然后调用
参考使用
- controller 暴露
export { BookConfiguration as Configuration } from './configuration';
export { APIController as Controller } from './controller/api.controller'; // 自定义组件的controller
export * from './service/book.service';
- 配置处理 自定义组件使用主应用的配置
export class BookConfiguration {
@Config("tenant")
tenantConfig:TenantContext // 自定义的接口
async onReady() {
console.log('Current tenantId:', this.tenantConfig);
console.log('BookConfiguration is ready');
}
}
- 主应用服务的注入
import { Inject, Controller, ApplicationContext, Get, IMidwayContainer } from '@midwayjs/core';
import { BookService } from '../service/book.service';
@Controller('/bookapi')
export class APIController {
@Inject()
bookService: BookService;
@ApplicationContext()
appContext: IMidwayContainer;
constructor() {
console.log('APIController initialized');
}
@Get('/get_book')
async getBook() {
const book = await this.bookService.getBookById();
// 通过appContext ioc 容器或者服务,注意是异步方法
const userService = await this.appContext.getAsync("userService")
console.log('Retrieved UserService from ApplicationContext:', userService);
let userResult = await (userService as any).getUser({ uid: 1 });
return { success: true, message: 'OK', data: book,user:userResult };
}
}
说明
以上一些特点实际官方文档都有说明,但是利用好这些特性,我们的自定义组件开发就比较方便了,可以实现灵活的业务集成,以及功能复用
浙公网安备 33010602011771号