Egg.js自定义服务

在app目录中新建service文件夹,在service文件夹下新建student.js,我们引入egg里的Service,并新建StudentService类继承自Service

const Service = require('egg').Service;

class StudentService extends Service{

    // 模拟数据库获取
    async index(){
        return {
            id:100,
            name:'huangbaokang',
            city:'jiangxi'
        }
    }
}

module.exports = StudentService;

前端调用StudentService
我们这里在学生管理模块首页进行调用。

在学生控制器student.js文件中,修改index方法

async index(){
        const { ctx } = this;
        //ctx.body = 'student index';
        // 调用Service获取数据
        const res = await ctx.service.student.index();
        ctx.body = res;
    }

ctx.service.student命名小写,这个是约定。index方法返回模拟从数据库中获取的数据。
自定义服务之后,就可以在多个控制器里进行调用,方便模块开发。

发布了1184 篇原创文章 · 获赞 272 · 访问量 203万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/104171294