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

在app.js中自定义Controller基类的私有方法后,controller中无法使用 #1755

Closed
SAHX opened this issue Nov 28, 2017 · 5 comments · Fixed by #1771
Closed

在app.js中自定义Controller基类的私有方法后,controller中无法使用 #1755

SAHX opened this issue Nov 28, 2017 · 5 comments · Fixed by #1771
Assignees

Comments

@SAHX
Copy link

SAHX commented Nov 28, 2017

  • Node Version: v8.0.0

  • Egg Version: v2.0.0

  • Plugin Name: 无

  • Plugin Version: 无

  • Platform: iMac

  • Mini Showcase Repository: 无

这是按照文档自定义 Controller 基类 的代码写的:

// app.js

module.exports = app => {
  class CustomController extends app.Controller {

    success(data) {
      this.ctx.body = {
        success: true,
        data,
      };
    }

    notFound(msg) {
      msg = msg || 'not found';
      this.ctx.throw(404, msg);
    }
  }
  app.Controller = CustomController;
}

// app/controller/home.js

'use strict';

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

class HomeController extends Controller {
  async index() {
    this.success({msg: 'hi egg!'})
  }
}

访问 http://127.0.0.1:7001/
报错:2017-11-28 21:25:04,471 ERROR 58662 [-/127.0.0.1/-/8ms GET /] nodejs.TypeError: this.success is not a function

但是这么写就可以:

// app/controller/home.js

'use strict';

module.exports = app => {
  const Controller = app.Controller;

  class HomeController extends Controller {
    async index() {
      this.success({msg: 'hi egg!'})
    }
  }
  return HomeController
}
@popomore
Copy link
Member

如果不想用函数的方式,可以直接 require 基类

这篇文档也要改下

@dead-horse
Copy link
Member

同时需要 require('egg').Controller = CustomController

@dead-horse
Copy link
Member

文档我等下看看怎么优化一下

@atian25
Copy link
Member

atian25 commented Nov 28, 2017 via email

@atian25
Copy link
Member

atian25 commented Nov 29, 2017

@popomore @dead-horse

https://github.com/eggjs/egg/blob/docs-2.x-async-function/lib/egg.js#L123

这几个是不是改为 setter 和 getter 好点?

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

Successfully merging a pull request may close this issue.

4 participants