使用Ionic 2

时间:2016-10-06 12:01:07

标签: angular ionic-framework ionic2

我有一个像这样的基本页面组件:

import { Component } from "@angular/core";
import { Events } from "ionic-angular";
import { Socket } from "../../../Socket/Socket";

@Component({
    selector: "page-leaderboard",
    templateUrl: "Leaderboard.html"
})
export class LeaderboardPage {

    constructor(public events: Events, public socket: Socket) {
    }

    ionViewWillEnter() {
        this.events.subscribe("leaderboard.open", () => {
            console.log("leaderboard.open");
        });
    }

    ionViewDidEnter() {
        this.socket.emit("get leaderboard data");
    }
}

但是,此代码存在问题。它注入类而不是类实例,这意味着我必须使用

constructor(public events: Events, public socket: Socket) {
    this.socket = new Socket;
    this.socket.connect();
}

在构造函数上使其工作。

我不想创建socket对象的新实例。理想情况下,它应该是通过引用传递给组件的单例。

我该怎样做呢?

// app.components.ts or app.modules.ts, or somewhere else
import { Socket } from "App/Socket/Socket";

let socket = new Socket; // put this into Angular's DI Container somehow
socket.connect().then(() => {
   console.log("Socket connected");
});

---

// Components
constructor(public events: Events, public socket: Socket) {
    this.socket = Socket; // "class instance" should be injected here
}

非常感谢!

0 个答案:

没有答案