Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controller中下面exports.index写法ok,但是用类的写法就不支持么? #15

Closed
DragWeb opened this issue Aug 4, 2017 · 5 comments

Comments

@DragWeb
Copy link

DragWeb commented Aug 4, 2017

// exports.index写法ok
// exports.index = function* (ctx) {
// yield ctx.render('index/index.js');
// };

// class写法不ok
module.exports = app => {
class homeController extends app.Controller {
* index() {
console.log('app=====', app)
yield this.ctx.render('index/index.js', this.ctx);
}
}

return homeController;
};

@jacksky007
Copy link

jacksky007 commented Aug 4, 2017

@DragWeb 你的示例代码不全,参照 egg 文档,你的代码应该是这样

const Controller = require('egg').Controller
module.exports = class homeController extends Controller {
  * index() {
    console.log('app=====', app)
    yield this.ctx.render('index/index.js', this.ctx);
  }
};

@DragWeb
Copy link
Author

DragWeb commented Aug 5, 2017

@jacksky007 thanks!

@DragWeb DragWeb closed this as completed Aug 5, 2017
@DragWeb
Copy link
Author

DragWeb commented Aug 5, 2017

hi @jacksky007 controller层按下面的写法,那router.js如何写呢?

const Controller = require('egg').Controller
module.exports = class homeController extends Controller {
  * index() {
    yield this.ctx.render('index/index.js', this.ctx);
  }
};

这样写找不到路由,直接404了

const controller = app.controller
app.get('/', controller.home.home.index)

router.js文件中this.ctx是一个空对象,拿不到homeController

我的目的就是想跟controller调用Service中的方法一样(ctx.service.biz.user)ctx.controller.xx.xx

@DragWeb DragWeb reopened this Aug 5, 2017
@jacksky007
Copy link

@DragWeb 就你贴的内容我也不知道是啥问题,egg 路由文档是这样的

module.exports = app => {
  app.get('/', app.controller.home.home.index)
}

我刚接触egg,还很不熟悉,但router.js中肯定是不能访问context的,context是请求级别的对象,而router.js是整个egg框架启动过程中使用的初始化信息,所以想在router.js用this.context方式肯定是不对的。

@DragWeb
Copy link
Author

DragWeb commented Aug 6, 2017

@jacksky007 嗯,是的,确实在router.js拿不到context,看来只看按文档方式做了,感谢感谢!
@hubcarl 建议在controller与router可以用class方式做那就更好了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants