在Angular 2(Ionic 2 / Angular 2 / Typescript)的服务中注入服务时如何传递依赖关系的参数

tymspy

我正在制作一个示例应用程序,以连接打字稿中ionic 2中的Websocket服务器。链接到回购

我的要求是在应用程序启动期间建立websocket连接

我正在使用angular2-websocket创建连接。

参考文献:

  1. http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

  2. http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

我收到一个错误“无法解析'$ WebSocket'(String,Array,?)的所有参数。请确保所有参数都用Inject装饰或具有有效的类型注释,并且'$ WebSocket'用Injectable装饰。 ”

代码:app.ts

import {App, Platform} from 'ionic-framework/ionic';
import {TabsPage} from './pages/tabs/tabs';
import {ConnectionService} from './framework/connection/connection-service'
import {$WebSocket} from 'angular2-websocket/angular2-websocket';
import {bootstrap} from 'angular2/platform/browser';

// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type} from 'angular2/core';


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {}
})
export class MyApp {
  rootPage: Type = TabsPage;

  constructor(platform: Platform, private conn : ConnectionService) {
    platform.ready().then(() => {
      this.conn.connect();
    });
  }
}
bootstrap(MyApp, [$WebSocket, ConnectionService]);

连接服务

import {Injectable, Component, Inject} from 'angular2/core';
import {$WebSocket} from 'angular2-websocket/angular2-websocket';
import {bootstrap} from 'angular2/platform/browser';

@Injectable()
export class ConnectionService {

    private _status: number;

    //private connection: $WebSocket;

    constructor( private connection : $WebSocket = new $WebSocket("ws://echo.websocket.org") ) {

    console.log("Starting connection");

   //this.connection = new $WebSocket("ws://echo.websocket.org");

    this.connection.onClose(this.onCloseHandler);
    this.connection.onError(this.onErrorHandler);
    this.connection.onOpen(this.onOpenHandler);
    this.connection.onMessage(this.onRecieveHandler, {});

}
...
public connect() {
    this.connection.connect(true);
}
...
}
bootstrap(ConnectionService, [$WebSocket]);
tymspy

解决我的问题的方法是使用@App()注解(特定于离子)提供程序字段,而不使用引导程序

bootstrap(ConnectionService, 
    [provide($WebSocket, useValue: new WebSocket("ws://echo.websocket.org")]);

例如。

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers : [ provide( $WebSocket, { useValue: new $WebSocket("ws://echo.websocket.org") }), ConnectionService]
})

工作样本可以在这里找到

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章