当前,我正在使用ng2-signalr模块(https://www.npmjs.com/package/ng2-signalr)开发ionic3信号器客户端应用程序。当我使用“ ionic serve”命令运行时,该应用程序可以成功与服务器通信,并且完全没有错误。但是当我使用“ ionic cordova run android”时,问题开始了,无法连接到我的Signalr服务器。
我已经在服务器端的web.config文件中启用了CORS。
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
下面是我的聊天中心
public class Myhubby : Hub
{
public void Send(string name, string message)
{
Clients.All.recMessage(message);
}
public void recMessage(string message)
{
Clients.All.recMessage(message);
}
}
这是离子app.module.ts文件。
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import 'expose-loader?jQuery!jquery';
import '../../node_modules/signalr/jquery.signalR.js';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { SignalRModule } from 'ng2-signalr';
import { SignalRConfiguration } from 'ng2-signalr';
export function createConfig(): SignalRConfiguration {
const c = new SignalRConfiguration();
c.hubName = 'myhubby';
// c.url = 'http://192.168.1.70:9999/';
c.url = "http://localhost:38490/";
c.logging = true;
// >= v5.0.0
c.executeEventsInZone = true; // optional, default is true
c.executeErrorsInZone = false; // optional, default is false
c.executeStatusChangeInZone = true; // optional, default is true
return c;
}
@NgModule({
declarations: [
MyApp,
HomePage,
ListPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp) ,
SignalRModule.forRoot(createConfig)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
ListPage
],
providers: [
StatusBar,
SplashScreen,
SignalRModule,
SignalRConfiguration,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
下面是主页ts文件。
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SignalR, IConnectionOptions, BroadcastEventListener } from 'ng2-signalr';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private _signalR: SignalR) {
}
connect_sub(){
let conx = this._signalR.createConnection();
let onMessageSent$ = new BroadcastEventListener('recMessage');
conx.listen(onMessageSent$);
onMessageSent$.subscribe((message: string) => {
alert(message);
});
conx.status.subscribe((s) => {
alert("connection");
console.warn(s.name);
});
conx.start().then((c) => {
console.log(c);
});
}
}
connect_sub函数链接到该按钮,并且在按下按钮时起作用。
当它与浏览器一起正常工作时,为什么它不能与模拟器一起工作。
干杯! 青蛙