Angular 6 - socket.io-клиент не работает в сервисе только в тесте и ngModel то же самое почитается - PullRequest
0 голосов
/ 29 сентября 2018

У меня какая-то странная проблема, я пытаюсь установить соединение с сервером js узла, который у меня есть с сокетами, но он не работает, когда я выполняю подачу кода, он вообще не показывает html, в режиме 'ng test' это работает как-то, и я понятия не имею, почему.

еще одна странная проблема заключается в том, что ngModel не работает в тесте ng, а при обслуживании он работает ... что происходит?!

app.component.ts

import { Component, OnInit } from '@angular/core';
import {SocketService} from './socket.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  public ioConnection: any;
  public messages: string[] = [];
  public message: string = "hell";
  constructor(private socketService: SocketService) { }

  ngOnInit(): void {
    this.initIoConnection();
  }

  private initIoConnection(): void {
    this.socketService.initSocket();

    this.ioConnection = this.socketService.onMessage()
      .subscribe((message: string) => {
        this.messages.push(message);
      });
  }

  public newMessage() {
    this.messages.push(this.message);
    this.socketService.send(this.message);
    this.message = "";
  }

}

socket.service.ts

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/internal/Observable';
import {Observer} from 'rxjs/internal/types';

import * as socketIo from 'socket.io-client';

const SERVER_URL = 'http://localhost:4600/';

@Injectable({
  providedIn: 'root'
})
export class SocketService {
  private socket;

  public initSocket(): void {
    this.socket = socketIo(SERVER_URL);
  }

  public send(message: string): void {
    this.socket.emit('message', message);
  }

  public onMessage(): Observable<string> {
    return new Observable<string>(observer => {
      this.socket.on('message', (data: string) => observer.next(data));
    });
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

Messages:<br>
<span *ngFor="let message of messages">{{message}}</span>
<br>
<input type="text" [(ngModel)]="message" />
{{message}}
<button (click)="newMessage()">Add</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...