如何将此变量从类方法导出到另一个文件?

时间:2019-02-22 07:03:39

标签: javascript node.js angular reactjs

  1. 请转到此代码的第60行或(此变量位于for循环内的Amit),我想要该变量名 导出到另一个文件中,但是我不能使用tat可变值来 其他文件。当我通过要求它显示未定义来做到这一点时。

    class FetchData {
    
        constructor(device_id, header) {
            this.device_id = device_id;
            this.header= header;
        }
    
        services() {
            // Get Device Details by deviceId
            return httpRequest({ 
                method  : 'get', 
                json    : true,
                url     : `${config.url.usermgmt_api}/device/${this.device_id}`,
                headers : { 'x-access-token': this.header }
            }).then( response => {
                if(response.hasOwnProperty('auth') && !response.auth) {
                    throw new Error(response.message);
                }
                let thingGreenLinks = [];
    
                // Current Active TG into the Array
                if(response.hasOwnProperty('mapping')) {
                    //We have to scroll through the mapping and return the shortcode and thingid and ports to connect
                    thingGreenLinks.push(response.mapping[0].TG_Port.split(/_/)[0]);    
                } else {
                    throw (response.message)? response.message : 'No mapping found. Device ID: '+ deviceid;
                }
    
    
                // Check mapping history 
                if(response.hasOwnProperty('map_history') && response.map_history.length > 0) {
                    response.map_history.reverse().map( record => { 
                        thingGreenLinks.push(record.mapping[0].TG_Port.split(/_/)[0]) 
                    })
                }
                return thingGreenLinks;
            }).then(async tg_ids => {
                logger.info('Fetching Hardware IDs of ThingGreen ...');
                let Hardware_IDs = [];
    
                for (let i = 0; i <= tg_ids.length - 1; i++) {
                    await fetchHardwareID(tg_ids[i], this.header)
                   .then( response => { Hardware_IDs.push(response.HardwareId) })
    
                   let Amit = 'amit'
                 module.exports = { amit : Amit}
    
                }
                logger.info('Received Following Hardware IDs :\n'+Hardware_IDs.join('\n'));
                return Hardware_IDs;
            })
            .catch( err => Promise.reject(new Error(err.message)));
        } } exports.FetchData = FetchData;
    
    1. 列表项

1 个答案:

答案 0 :(得分:0)

您可以在班级中拥有一个变量,   在您的服务函数中为其赋值

class FetchData {

    constructor(device_id, header) {
        this.device_id = device_id;
        this.header= header;
        this.amit = "";
     }

   services() {
       //your sevices code
       this.amit='amit'
     }


} exports.FetchData = FetchData;

然后在另一个导入FetchData的文件中,可以使用object.varible名称进行访问。

    var fetchDataObject = new FetchData(device_id, header);
     fetchDataObject.amit //this is your variable amit