Angular 2/4双向数据绑定在observable中不起作用

时间:2017-06-28 18:35:14

标签: javascript angular angular2-template

Hi,我使用第三方库simple-peer,我在角度4中声明了declare var SimplePeer: any;,而navigator.n.mediaDevices.getUserMedia()中的所有逻辑都被扭曲了(要求用户提供视频) / audio permission)这是异步函数,问题是SimplePeer返回了我需要在html中使用的一些数据但是我不能只用console.log()输出html中的数据,这里是代码app.component.html:

<input type="text" [(ngModel)]="targetpeer">
<button (click)="connect()">Connect</button>
<button (click)="message()">Send Message</button>



<p>{{texttoken}}</p>





<video #myVideo></video>

忽略视频,除了{{texttoken}}没有更新外,一切正常,它显示我在app.component.ts中设置的初始虚拟数据:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @ViewChild('myVideo') myVideo:any; 

  texttoken :any = 'initial dummy value'; 
  targetpeer: any;
  peer: any;
  n = <any>navigator;

  ngOnInit() {


    let video = this.myVideo.nativeElement;
    let peerx: any;
    let onJSTokenChange = new Subject(); // create new observable to obsere any changes to assign a value to texttoken
    onJSTokenChange.subscribe((value)=>{

        this.texttoken = value;
        console.log(this.texttoken);

    });


    this.n.getUserMedia = (this.n.getUserMedia || this.n.webkitGetUserMedia || this.n.mozGetUserMedia || this.n.msGetUserMedia);
    this.n.mediaDevices.getUserMedia({video:true, audio:true}).then( function(stream) {
    peerx = new SimplePeer ({
      initiator: location.hash === '#init',
      trickle: false,
      stream:stream
    })

    peerx.on('signal', function(data) {
      console.log(JSON.stringify(data));
      // here I pass that data to the observable  
      onJSTokenChange.next(JSON.stringify(data));
      this.targetpeer = data;
    })

    peerx.on('data', function(data) {
      console.log('Recieved message:' + data);
    })

    peerx.on('stream', function(stream) {
      video.src = URL.createObjectURL(stream);
      video.play();
    })

    }, function(err){
    console.log('Failed to get stream', err);
    });










  }

  connect() {
    this.peer.signal(JSON.parse(this.targetpeer));
  }

  message() {
    this.peer.send('Hello world');
  }





}

在这里你可以看到我将虚拟数据分配给我的texttoken,而不是创建一个可观察的onJSTokenChange来跟踪某些内容是否发生变化以将值赋给texttoken,这个可观察的获取peerx.on('signal'代码执行时的数据,然后onJSTokenChange.subscribe获取该数据,console.log()数据按预期工作,但the.texttoken也会收到该值,但确实如此不进行双向绑定并且不更新<p>{{texttoken}}</p>即使我console.log()它并且它返回正确的值,请帮助我们整天想出来:(

1 个答案:

答案 0 :(得分:1)

我刚刚从angular / core导入了ChangeDetectorRef并注入了

constructor(private detector:ChangeDetectorRef){}

在我的

中使用它
onJSTokenChange.subscribe((value)=>{

        this.texttoken = value;
         this.detector.detectChanges();

    });

并且它有效,感谢@ AJT_82和@LLai