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

前端之家收集整理的这篇文章主要介绍了如何在Angular 2中注入服务时传递依赖参数(Ionic 2 / Angular 2 / Typescript)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在制作一个示例应用程序,以便在typescript中的ionic 2中连接到websocket服务器.链接repo

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

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

参考文献:

> http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html
> http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

我收到错误“无法解析’$WebSocket’的所有参数(字符串,数组,?).确保所有参数都使用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]);

connection-service.ts

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]);
我的问题的解决方案是使用@App()Annotation(特定于离子)提供程序字段而不是使用bootstrap
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]
})

工作样本可以找到here

原文链接:https://www.f2er.com/angularjs/141214.html

猜你在找的Angularjs相关文章