ng2-signalr错误:无法连接。错误:协商请求期间出错

时间:2017-06-20 14:53:49

标签: asp.net angular signalr

我正在使用this lib并且我将signlaR配置为this demo并且没有任何崩溃,但是当我访问pageComponent时它无法与SignalRServer连接,服务器工作,我将其用于其他事情,但是signalR不起作用。 我配错了什么?

我的app.module.ts

[...]
//external libs
import { SignalRModule } from 'ng2-signalr';
import { SignalRConfiguration } from 'ng2-signalr';
import { ConnectionResolver } from "app/route.resolver";

//ng2-signalr v2.0.0
export function createConfig(): SignalRConfiguration {
  const c = new SignalRConfiguration();
  c.hubName = 'Ng2SignalRHub';
  c.qs = { user: 'donald' };
  c.url = 'http://localhost:54755';
  c.logging = true;
  return c;
}

@NgModule({
    declarations: [
        AppComponent,
        HomePage,
        LoginPage,
        CustomerPage,
        ConfigurationPage,
        OfferPage,
                [...]
                DocumentModalAcceptComponent,
        OfferModalComponent,
        OfferCliModalComponent
         ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule,
        Routing,
        SignalRModule.forRoot(createConfig)
    ],
    providers: [
        ConnectionResolver,
        AuthService,
        { provide: LOCALE_ID, useValue: 'pt-BR' }
    ],
    bootstrap: [AppComponent]
})

my page.component.ts

import { SignalRConnection, BroadcastEventListener, ConnectionStatus } from 'ng2-signalr';
import { ActivatedRoute } from "@angular/router";

@Component({
    selector: 'app-offer-cli',
    templateUrl: './offer-cli.component.html',
    providers: [DataService,Helper]
})
export class OfferCliComponent implements OnInit {
    private errors: any[] = [];
    private modalIsOpen: boolean;
    [...]
    private user: any;
    private data: any;

    private _connection: SignalRConnection;
    private chatMessages: ChatMessage[];
    private statuses: any;



    constructor(private service: DataService, private helper: Helper, private route: ActivatedRoute) {
          this._connection = this.route.snapshot.data['connection'];
       }

    ngOnInit() {

        // 1.create a listener object
        let onMessageSent$ = new BroadcastEventListener<ChatMessage>('OnMessageSent');

        // 2.register the listener
        this._connection.listen(onMessageSent$);

        // 3.subscribe for incoming messages
        onMessageSent$.subscribe((chatMessage: ChatMessage) => {
            this.chatMessages.push(chatMessage);
        }); 

        this._connection.status.subscribe((status: ConnectionStatus) => {
            this.statuses.push(status);
        });

        //this._connection.start();

        this._connection.errors.subscribe((error: any) => {
            this.errors.push(error);
            console.log("erro de conexão com o signalR")
            console.log(error)
        });
    }
[...]
export class ChatMessage {
  constructor(public user: string, public content: string) {}
}  

我的app.routing.ts

[...]
import { ConnectionResolver } from './route.resolver';

import { AuthService } from './services/auth.service';

const appRoutes: Routes = [
    { path: '', component: LoginPage },
    { canActivate: [AuthService], path: 'home', component: HomePage },
    { canActivate: [AuthService], path: 'customer', component: CustomerPage },
    { canActivate: [AuthService], path: 'offer', component: OfferPage },
    { canActivate: [AuthService], path: 'client/offer', component: OfferPageCli,resolve: { connection: ConnectionResolver } },
    { canActivate: [AuthService], path: 'configuration', component: ConfigurationPage },
    { canActivate: [AuthService], path: 'contact', component: ContactPage },
    { canActivate: [AuthService], path: 'document', component: DocumentPage }

];

export const RoutingProviders: any[] = [];
export const Routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

我的路线.resolver.ts

import { Resolve } from '@angular/router';
import { SignalR, SignalRConnection } from 'ng2-signalr';
import { Injectable } from '@angular/core';

@Injectable()
export class ConnectionResolver implements Resolve<SignalRConnection> {

    constructor(private _signalR: SignalR)  { }

    resolve() {
        console.log('ConnectionResolver. Resolving...');
        return this._signalR.connect();
    }
}

我的.angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "macaw-web-backoffice"
  },
  "apps": [
    [...]
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/signalr/jquery.signalR.js"
        ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
[...]

我正在使用 jquery@3.2.1 ng2-signalr@2.0.6 signalr@2.2.2

这是我的hub.cs

namespace Macaw.WebApi.hubs
{
    [HubName("Ng2SignalRHub")]
    public class Ng2SignalRHub : Hub 
    {

        public override Task OnConnected()
        {

            Trace.TraceInformation("Ng2SignalRHub - OnConnected");

            var user = GetAuthenticatedUser();

            Clients.All.OnUserConnected(user);

            return base.OnConnected();
        }

        private string GetAuthenticatedUser()
        {
            var username = Context.QueryString["user"];
            if (string.IsNullOrWhiteSpace(username))
                throw new System.Exception("Failed to authenticate user.");

            Trace.TraceInformation("GetAuthenticatedUser :" + username);

            return username;
        }


        // chat
        public void Chat(ChatMessage message)
        {
            // broadcast to all clients
            Clients.All.OnMessageSent(new ChatMessage("Hannes", "Message"));
        }



    }

    public class ChatMessage
    {
        public ChatMessage(string user, string message)
        {
            User = user;
            Message = message;
        }

        public string User { get; set; }
        public string Message { get; set; }
    }
}

我没有将集线器设置为控制器

当我打开我的组件OfferCliComponent时,我在控制台Imgur中收到它 非常感谢你

0 个答案:

没有答案