0

我在构造函数中定义了一个类变量,它包含对导入的类实例的引用。

但是,当我尝试在我的类方法中访问该变量时,我一直在获取undefined该变量。

导出类

import models from '../../database/models'

const {User} = models;

class UserRepository {
  constructor(){
    this.model = User;
  }

 async create({firstname, lastname, email, isadmin, password}){
  return await this.model.create({firstname, lastname, email, isadmin, password})
  }
}

export default new UserRepository();

使用导出的类进行类

import repository from './repository';
import { sendSuccessMessage } from '../../utils'

class UserController {
  constructor() {
    this.model = repository;
  }

  async createUser({ body }, res, next) {
    try {
      const result = await this.model.create(body);
      sendSuccessMessage(res, 200, result);
    } catch( e ){
      next(e)
    }
  }
}

export default new UserController();

但是,使用下面指定的变量repository目录:createUser

const result = await repository.create(body);

按预期工作。

当前调用链

// routes.js file
import controller from './controller'

export default [
  {
    path: '/signup',
    method: 'post',
    handlers: [controller.createUser] // createUser from class UserController
  }
]


// utitlity.js file
export const routesLoader = (routes, router) => {
 for (const route of routes) {
   const { path, handlers, method } = route;
   (router)[method](path, handlers);
 }
};

// app.js file
import express from 'express';
import routes from './routes.js';
import { routesLoader } from './utils';

const router = express.Router();

routesLoader(routes, router);

// server.js file
import http from 'http';
import app from './app';

const { PORT = 3000 } = process.env;

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`server listening on localhost: ${PORT}`);
});

错误

TypeError: Cannot read property 'create' of undefined
at _callee$ (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user/controller.js:16:39)
at tryCatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:45:40)
at Generator.invoke [as _invoke] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:271:22)
at Generator.prototype.<computed> [as next] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\regenerator-runtime\runtime.js:97:21)
at asyncGeneratorStep (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
at _next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:25:9)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\@babel\runtime\helpers\asyncToGenerator.js:21:12
at createUser (C:\Users\MYPC\Downloads\moch-shop-api-master\components\user\controller.js:70:28)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\express\lib\router\index.js:275:10)
at cors (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:188:7)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:214:15)
at C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\MYPC\Downloads\moch-shop-api-master\node_modules\cors\lib\index.js:199:9)

使用的技术

@babel/node: "^7.8.4"
terminal: git bash
Os: windows
4

3 回答 3

0

怎么UserController.createUser称呼?听起来它this没有正确设置。假设我们这样初始化类:

const userController = new UserController();

然后,丢失的一个来源this可能是您仅传递对该方法的确切引用

setImmediate(userController.createUser);

而不是保留的方式this

setImmediate(() => {
   userController.createUser()
});

换句话说,您想使用点表示法调用方法并涉及类实例。

于 2020-02-18T13:26:13.693 回答
0

您的方法 create 是一个实例方法。它需要是静态的才能工作

于 2020-02-18T12:56:28.040 回答
0

首先,您需要在UserRepository使用前正确导入。

import UserRepository from 'path to UserRepository class';

然后self在您的函数中使用如下:

async createUser({ body }, res, next) {
 const self = this;
 try {
   const result = await self.model.create(body);
   sendSuccessMessage(res, 200, result);
 } catch( e ){
   next(e)
 }
}

与您的 createUser() 函数self相比,我认为使用起来更好。this

于 2020-02-18T12:58:11.600 回答