2017-05-01 1 views
2

私はWeb開発の新人で、最近約束を守り始めました。下のコードでは数ミリ秒後に解決されますが、ブラウザを更新してすぐにボタンをクリックすると "未定義"このようなことが想定されているのか、それとも解決が間違っているか、実装が間違っている場合を除き、通常は約束どおりに結果を出す必要はありませんか?約束事の正確な行動は何ですか?

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


@Component({ 
    selector: 'my-app', 
    template: `<button (click)="showMyId()">Next</button> 
    <h1>S {{myId}} </h1>`, 
}) 
export class AppComponent implements OnInit { 
    thepeer: any; 
    myId: any; 

    ngOnInit(){ 
    this.thepeer = new Peer({key: '1h907r5xnvims4i'}); 
    this.showMyId(); 
    } 

    showMyId(){ 
    this.getMyId().then((id)=>{ 
     this.myId = id; 
     console.log(this.myId); 
    }) 
    } 

    getMyId(){ 
    return new Promise((resolve, reject)=>{ 
     resolve(this.thepeer.id); 
    }) 
    } 



} 

ご協力いただきますようお願い申し上げます。

答えて

2

あなたがIDを使用する前に発射するopenイベントを待機する必要があります。

getMyId(){ 
    return new Promise((resolve, reject)=>{ 
     this.thepeer.on('open', (id) => { 
      resolve(this.thepeer.id); 
     }); 
    }) 
} 

は、マニュアルを参照してください:http://peerjs.com/docs/#start

+0

はどうもありがとうございました! –

関連する問題