如何在Angular2,Ionic2中只显示一个项目

时间:2017-04-19 14:59:32

标签: node.js angular socket.io ionic2

请关注我的问题,因为我是Angular的新手并且我不确切地知道问题出在哪里,我已经尝试谷歌寻求解决方案,但没有好运,基本上我和#39; m运行带有socket.io的简单NodeJS服务器:

服务器

var socket = require('socket.io'),
    http = require('http'),
    server = http.createServer(),
    socket = socket.listen(server);
    var msgProva = 2;

socket.on('connection', function(connection) {
    console.log('User Connected');
    socket.emit('prova', msgProva);


    connection.on('message', function(msg){
        socket.emit('message', msg);
    });
    connection.on('sValue', function(value){
        console.log('sValue', value );
        socket.emit('sValue', value);
    });

});

server.listen(3000, function(){
    console.log('Server started');
});

和我的客户端TS代码: 的 HOME.TS

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';
import * as io from 'socket.io-client';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  socket:any
  chat_input:string;
  chats = [];
  prova = [];
  slideValueBadge = [];


  constructor(public navCtrl: NavController) {
      var a;
      this.socket = io('http://localhost:3000');

   this.socket.on('message', (msg) => {
     console.log("message", msg);
     this.chats.push(msg);
   });

   this.socket.on('prova', (msgProva) => {
       console.log("msgProva", msgProva);
       this.prova.push(msgProva);
   });

   this.socket.on('sValue', (value) => {
       let index: number = this.slideValueBadge.indexOf(value);
       if (index != -1) {
           a = this.slideValueBadge.splice(index, 1);
       }
       console.log("sliderValue:", value);

   });
  }

  send(msg) {
        if(msg != ''){
            this.socket.emit('message', msg);
        }
        this.chat_input = '';
  }
  cValue(event, nome) {
      console.log("SliderValue", event._valA);
      this.socket.emit('sValue', event._valA);
  }
}

home.html的

<ion-content padding>
  <ion-item>
    <ion-range [(ngModel)]="brightness" (ionChange)="cValue($event, 'slider1')">
      <ion-icon range-left small name="water"></ion-icon>
      <ion-icon range-right name="water"></ion-icon>
    </ion-range>
  </ion-item>
  Flusso d'acqua
  <ion-badge color="secondary">{{slideValueBadge}}</ion-badge>
    <ion-list>
      <ion-item *ngFor="let message of chats">{{message}}</ion-item>
    </ion-list>

    <ion-item>
      <ion-input type="text" [(ngModel)]="chat_input" placeholder="Enter message"></ion-input>
    </ion-item>

    <button ion-button block (click)="send(chat_input)">Send</button>
</ion-content>

这就是我看到的结果:

enter image description here

如何只显示一个值? (最后一个)?

2 个答案:

答案 0 :(得分:1)

基本上,您将徽章绑定到数组(slideValueBadge = [])。

只需将绑定值更改为number,然后使用socket.on方法进行更新。

希望这可以帮到你

答案 1 :(得分:0)

显然这是解决方案,如果编码好或坏,不知道如何:

<ion-badge color="secondary">{{slideValueBadge[slideValueBadge.length -1]}}</ion-badge>

没有*ng-if