繁体   English   中英

来自未定义的导入类的方法

[英]Method from imported class undefined

我正在尝试将第三方API集成到我的meteor.js应用程序中。 因此,想法是,在/blog路由上,应用程序应调用外部类的方法。

router.js

import blog from '../imports/scripts/blog';
FlowRouter('/blog', {
  name: 'blog',
  action: function(params) {
    blog.init(); // here I get the error "init is not a function" (it's undefined)
  }
});

blog.js

export default class Blog {
  constructor(){
    ...
  }

  init() {
    console.log('init blog api');
    ...
  }
}

我正在使用最新的流星(1.4.2.3)和以下npm软件包来启用ES2015:

"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-preset-es2015": "^6.18.0",
"babel-runtime": "^6.18.0",
"meteor-node-stubs": "^0.2.4",
"webpack": "^1.13.3"

我在设置中是否缺少无法调用blog.init()

我认为您尝试导入类(不是类实例)。 因此,您不能调用方法。

将您的blog.js更改为:

class Blog {
  constructor(){
    ...
  }

  init() {
    console.log('init blog api');
    ...
  }
}
export default new Blog();

因此,Yan Mayatskiy和Gothdo在其评论中对此做出了回答,谢谢。 如果有人在寻找正确的答案:

我需要实例化导入的类,如下所示:

import Blog from 'blog';
const blog = new Blog();
blog.init();

如果要导出一个类,则需要在以后实例化它,除非该类具有某些静态方法。

让我们假设这是一个只有静态方法的“ helper”类。

export class Logger {
    static info(message) {
        console.log(`Info: ${message}`);
    }

    static error(message) {
        console.log(`Error: ${message}`);
    }
}

export default Logger;

因此,您可以导入它并立即使用它。

import Logger from "../../../../utils/Logger";
...
Logger.Info("...");

暂无
暂无

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

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