**注:**使用service和config前无需引入相关文件;
vscode安装egg.js插件,快捷生成service文件
@file(news.js)
const Service = require('egg').Service;
class NewsService extends Service {
async getNewsList() {
let list = [1, 2, 3];
return list;
}
}
module.exports = NewsService;
class NewsController extends Controller {
async index() {
// service的使用:不用引入,已挂载再this上,this.service+文件名+方法名
let list = await this.service.news.getNewsList();
await this.ctx.render('news', { list })
}
}
module.exports = NewsController;
3.1 user服务
@file(user.js)
class UserService extends Service {
async getUserInfo() {
return {
name: '张三',
age: 20
}
}
}
3.2 news 服务调用user服务
class NewsService extends Service {
async getNewsList() {
// 调用user服务的数据
let user = await this.service.user.getUserInfo();
console.log('news-服务:--user: ', user);
}
}
module.exports = appInfo => {
const config = exports = {};
// config全局数据
config.api = 'http://zgl.api';
return {
...config,
};
};
class NewsController extends Controller {
async index() {
// 使用config的数据
let configtxt = this.config.api;
console.log('configtxt: ', configtxt);
}
}