打字稿无法读取未定义的属性

时间:2018-12-05 17:52:40

标签: typescript

  

TypeError:无法读取未定义的属性“ ghNewPrMethod”

当我尝试将Webhook POST发送到Typescript应用程序时,出现上述错误。

我有以下控制器

import { GhStatusSchema } from '../models/gh-status.model';
import { Request, Response } from 'express';

import * as crypto from 'crypto';
import { Helpers } from '../helpers';
import { GhNewPrMethod } from '../methods/gh-new-pr.method';

import { GitHubConfig } from '../../config/github';

const secret: string = GitHubConfig.secret;

export class GhNewPrController {
  public helpers: Helpers = new Helpers();
  public ghNewPrMethod = new GhNewPrMethod();

  public post(req: Request, res: Response) {
    console.log(111);
    this.ghNewPrMethod.slackMessage(req.body, req.get('x-github-delivery'))
  } 
}

似乎this.ghNewPrMethod.slackMess存在问题,而this未定义。

** gh-new-pr.method.ts **

import * as Slack from 'slack-node';

import { GhMessageSchema } from '../models/gh-new-pr.model';
import { SlackConfig } from '../../config/slack';
import { UsersConfig } from '../../config/users';
import { Helpers } from '../helpers';

export class GhNewPrMethod {
  helpers: Helpers = new Helpers();

  public findSavedPR(id) {
    return new Promise((resolve, reject) => {
      GhMessageSchema.find({
        pull_request: id
      }, (err, message) => {
        if (err || message.length === 0) {
          reject(err);
        }
        resolve(message);
      });
    });
  }

  public slackMessage(payload, header) {
    console.log(payload);
  }
}

我使用另一个文件的原因是将控制器分解为另一个文件中的较小功能,因此某些功能可以重复使用,并使控制器看起来更整洁。

有人可以帮助我

编辑:

route.ts

import { Request, Response, NextFunction } from "express";
import { GhNewPrController } from '../controllers/gh-new-pr.controller';

export class Routes {

  public ghNewPrController: GhNewPrController = new GhNewPrController()

  public routes(app): void {

    app.route('/github')
      .post(this.ghNewPrController.post)

  }
}

1 个答案:

答案 0 :(得分:1)

您遇到了范围界定问题。要解决此问题,请使用bind函数,如下所示:

async function fetchUser(): Promise<User> { return new User(); } async function fetchCompany(): Promise<Company> { return new Company(); } class User { name:string } class Company { } type MyType<T> = { [K in keyof T]: ThenArg<T[K]> }; type ThenArg<T> = T extends Promise<infer U> ? U : any; export const combinePromises = function combinePromises<T>(obj: T): Promise<MyType<T>> { const keys = Object.keys(obj); const values = Object.values(obj); return Promise.all(values).then((results) => { const combinedResult: MyType<T> = {} as MyType<T>; results.forEach((result, i) => { const key = keys[i]; combinedResult[key] = result; }); return combinedResult; }); }; (async () => { const { user, company } = await combinePromises({ user: fetchUser(), company: fetchCompany() }); user.name; // we can access user.name since that's a member of User })();

来自developer.mozilla: bind()方法创建一个新函数,该函数在被调用时将其this关键字设置为所提供的值,并带有给定的参数序列调用新函数时提供的任何内容。

DEMO