简体   繁体   English

在类方法中使用时,类中的属性未定义

[英]Property in class is undefined when used in class method

Writing a test REST api with NodeJs for learning purposes. 出于学习目的,使用NodeJ编写测试REST api。 Currently I only have 1 route which accepts a parameter (which works fine). 目前,我只有1个接受参数的路由(工作正常)。

I'm using an express router to route the GET request to my controller. 我正在使用快递路由器将GET请求路由到我的控制器。 All of the routing is working as expected. 所有路由均按预期工作。

My ServiceController currently has a ctor function which accepts 2 parameters. 我的ServiceController当前具有一个ctor函数,该函数接受2个参数。 Both of these parameters are passed into the ctor function by the router during instantiation. 在实例化期间,这两个参数都由路由器传递到ctor函数中。

In the ServiceController ctor I store the parameters in to fields. 在ServiceController ctor中,我将参数存储到字段中。

The issue is, when I try to access these fields in a class method I'm getting a "TypeError: Cannot read property 'exec' of undefined". 问题是,当我尝试在类方法中访问这些字段时,出现“ TypeError:无法读取未定义的属性'exec'”。 I did write both of these values to the console to ensure that the ServiceController was receiving these values correctly (which it is). 我确实将这两个值都写入了控制台,以确保ServiceController正确接收了这些值。

So, i'm unsure why im getting this error when I attempt to access either "this.exec" or "this.logger" in the get method. 因此,我不确定为什么尝试在get方法中访问“ this.exec”或“ this.logger”时收到此错误。

Router 路由器

import express from 'express';
import { exec } from 'child-process-promise';
import ServiceController from '../controllers/serviceController';

let routes = (logger) => {
const router = express.Router();
let controller = new ServiceController(exec, logger);

router.route('/status/:name')
    .get(controller.get);

return router;
};

module.exports = routes;

ServiceController 服务控制器

export default class ServiceController {
constructor(childProcess, logger) {
    this.logger = logger;
    this.exec = childProcess;
}
get(req, res) {
    if (!req.params.name) {
        res.status(400).send('A service name was not provided');
    } else {
        this.exec(`sc query ${req.params.name}`).then(result => {
            if (result.stderr) {
                this.logger.log.warn(`stderr: ${result.stderr}`);
            }
            const regex = /STATE\s+:\s+\d+\s+(\w+)/;
            let [, status] = result.stdout.toString().match(regex);
            if (!status) {
                throw new Error('Status query unsuccessful');
            }

            let service = {
                name: req.params.name,
                status: status
            };

            res.json(service);
            return service;

        }).catch(error => {
            this.logger.log.error(`${error.name} ${error.message}`);
            res.status(500).send('An error occurred while executing command');
        });
    }
}
}

It's a problem of this context. 这是this情况下的问题。 You use the get method on a context which is not your ServiceController instance. 您在不是ServiceController实例的上下文中使用get方法。

Bind the method on your instance: 在您的实例上绑定方法:

router.route('/status/:name')
  .get(controller.get.bind(controller));

Or you can also define an arrow function in the ServiceController class. 或者,您也可以在ServiceController类中定义箭头功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM