【问题标题】:Call a method from another method at the same class in Typescript在 Typescript 的同一类中从另一个方法调用方法
【发布时间】:2019-07-28 17:24:44
【问题描述】:

我从 Typescript 开始,但在从同一类的另一个方法调用一个方法时遇到了问题。

读到这个问题,有人说要在方法名称前使用“this”,但在我的情况下它不起作用。

class PlaylistController {
  public async create(req: Request, res: Response): Promise<Response> {
    let artists = req.body.bands;
    artists = artists.split(',');

    const search = await Object.values(artists).map(
      (artistsName: string): void => this.searchArtists(artistsName),
    );

    return res.json(search);
  }

    private searchArtists = (artistName: string): void => {
      console.log(artistName);
    };

}
export default new PlaylistController();

编辑: 这是我用来调用我的方法的代码:

class App {
  public express: express.Application;

  public constructor() {
    this.express = express();
    this.middlewares();
    this.routes();
  }

  private middlewares(): void {
    this.express.use(express.json());
  }

  private routes(): void {
    this.express.get('/', (req, res): void => {
      res.send('API Rodando...');
    });

    this.express.post('/createPlaylist', PlaylistController.create);
  }
}

export default new App().express;

当我执行这段代码时,方法“searchArtists”没有被调用,我得到了错误:

UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“searchArtists”。 (节点:11941)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1) (节点:11941)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

所以,我不知道我做错了什么,希望你能帮助我。

【问题讨论】:

  • 当你说你执行代码的时候,是不是还有更多的代码没有贴在这里?因为您现在拥有的代码将无能为力。如果是这种情况,请发布调用该方法的代码。
  • @Collierre 谢谢你的回答,我添加了我用来调用我的方法的代码。
  • 您如何将PlaylistController 导入您的第二个文件?
  • @Collierre 导入没问题,我使用: import PlaylistController from './controllers/PlaylistController';
  • 嗯,我不确定。 this 应该解析为 create 方法中的 PlaylistController 实例。也许问题与this.express.post() 方法有关,虽然我不熟悉 Express。

标签: javascript node.js typescript


【解决方案1】:

您已将第二个参数中看似未绑定的方法PlaylistController.create 传递给this.express.post()。我假设 post() 的主体最终实际上调用了 unbound 方法,你的问题是它丢失了原始的 this 上下文,你得到了那个错误。 Passing around unbound methods is usually a mistake:

const x = {
  a() { console.log("a"); },
  b() { this.a(); }
};

这里,x 是一个具有ab 方法的对象。 b 方法调用this.a()。如果你直接调用b 作为x 的方法,一切都会如你所愿:

x.b(); // calling b as a property of x: "a"

但是如果你将x.b 方法保存到一个新变量中(或将其传递给函数参数等):

const xb = x.b; // xb is the b method of x, but it is not bound to x any longer.

你不能再直接调用它了:

try {
  xb(); // error at runtime: this is undefined
} catch (e) {
  console.log(e); //  "TypeError, this is undefined"
}

xb() 调用会给您一个运行时错误,因为当您直接调用函数而不是在某个其他对象的属性的上下文中时,this 上下文将是 undefined

幸运的是,这可以通过使用函数对象的bind() 方法来解决:

const xbBound = xb.bind(x); // explicitly bind the method to x again
xbBound(); // "a"

因此,对于您的情况,我会尝试将 PlaylistController.create 方法重新绑定到 PlaylistController 对象:

this.express.post('/createPlaylist', PlaylistController.create.bind(PlaylistController));

看看这是否有效。好的,希望有帮助;祝你好运!

Link to code

【讨论】:

  • 感谢您的回复,您的解决方案解决了我的问题。此外,我能够很好地理解在我的代码中产生错误的原因。
猜你喜欢
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 2017-10-17
  • 2013-10-08
  • 1970-01-01
  • 2010-11-02
  • 2011-01-14
相关资源
最近更新 更多