Typescript和Nodejs在控制器中返回未定义的

时间:2019-01-27 11:19:58

标签: node.js typescript express

我已经在stackoverflow和网络上进行了长期而艰苦的搜索,以寻求解决方案,但是找不到与我的问题类似的任何东西,可能是因为我是Typescript的新手,所以我仍然不完全舒服。

我正在尝试访问控制器中的this,并通过构造函数传递依赖项。

下面是我的pushNotificationRoute.ts文件,在其中我将apn.Provider注入控制器。

import { Request, Response, Application } from "express";
import { PushController } from "../controllers/push-controller";
import { Routes } from  "./routes-interface";
import *  as apn from "apn";
import { options } from "../configurations/options";

export class PushNotificationRoute implements Routes {

    public pushController: PushController
    public apnProvider: apn.Provider

    constructor() {
        this.apnProvider = new apn.Provider(options);
        this.pushController = new PushController(this.apnProvider);
    }

    routes(app: Application) {
        console.log("routes called -----")
        console.log(this.pushController);


        app.route('/notification')
        .get( this.pushController.getNotifications);

        app.route('/notification/send')
        .get(this.pushController.sendNotification);

    }
}

然后在控制器中执行以下操作

import {Request, Response } from 'express';
import *  as apn from 'apn';

export class PushController {

    public apnProvider: apn.Provider

    constructor(apnProvier: apn.Provider) {
        this.apnProvider = apnProvier
        console.log("new apn provider intialised ", this.apnProvider);
    }

    public getNotifications(req: Request, res: Response) {
        res.json({
            message: "get notificatoins"
        })
    }

    public sendNotification(req: Request, res: Response) {
        console.log("sendNotification controller function ", this.apnProvider); //crashes here when I call this.apnProvider

        let deviceToken = "898Y89F95BC283D2D933376E477AD38D9435552434WEQE633ADC4C58BED9B61"
        var note = new apn.Notification();

        note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
        note.badge = 3;
        note.sound = "ping.aiff";
        note.alert = "What are you doing now?";
        note.payload = {'messageFrom': 'John Appleseed'};
        note.topic = "com.mangafruit.compendium";
        console.log("sendNotification controller function ", this.apnProvider);

        this.apnProvider.send(note, deviceToken).then( (result) => {
            console.log("First notification Inshallah this will benifit my family & i")      
            res.json({
                message: "notification send successfully :D"
            })
        });

    }
}

当我在this函数中访问PushController().sendNotification()时,服务器崩溃

谢谢

0 个答案:

没有答案