2017-11-08 18 views
1

私は2つのコンポーネントを持っています。子コンポーネントにはイベントがあります(EventEmitter)。親コンポーネントには、長時間のメソッドを持つハンドラがあります。Observable callでイベント加入者の完了を待つ方法

私のメソッド(longTimeMethod)の実行が完了するのを待つ必要があります。方法は5秒近くまで続きます。

すべてのステップの実行に一貫して到達したい(1 - > 2 - > 3 - > 4 - > 5)。

しかし、今のシーケンスは1である - 私が使用して非同期待つアプローチを試みた> 3

@Component({ 
    selector: 'child-selector', 
    template: '<>********</>' 
}) 
export class ChildComponent{ 
    @Output() childEvent = new EventEmitter(); 

    someFunction() { 
     // Step 1: event emit 

     this.childEvent.emit(); 
     // Step 5: Subscribers execution finished 
     // Some code which should to reached after all event subscribers 
    } 
} 

@Component({ 
    selector: 'parent-selector', 
    template: '<child-selector (childEvent)="handleChildEvent()"></child-selector>' 
}) 

export class ParentComponent{ 
     // Step 2: handler start 
    handleChildEvent() { 
     // this.longTimeMethod return Observable<void> 
     this.myService.longTimeMethod() 
      .subscribe(() => { 
       // Step 3: Method executing finished 
      }); 
    // Step 4: Another code 
    } 
} 

> 2 - > 4 - - > 5:シーケンスが変更されたが、それはまだありません

async handleChildEvent() { 
    // this.longTimeMethod return Observable<void> 
    await this.myService.longTimeMethod().toPromise() 
     .then(() => { 
      // Step 3: Method executing finished 
     }); 
     // Step 4: Another code 
} 

を正しい:1 - > 2 - > 5 - > 3 - > 4 正しい動作を達成するには?

答えて

1

遅延手順5を実行すると、子からコールバックが発行されます。

export class ChildComponent{ 
    @Output() childEvent = new EventEmitter(); 

    someFunction() { 
    // Step 1: event emit 
    this.childEvent.emit(execStep5); 
    } 

    execStep5() { 
    // Step 5: Subscribers execution finished 
    // Some code which should to reached after all event subscribers 
    } 
} 

STEP3 STEP4 &については

handleChildEvent(execStep5) { 
    ... 
// Step 4: Another code 
execStep5(); 

準備ができて親にexecStep5を実行し、mapsubscribeを変更、そしては、STEP4とコールバックを購読して実行します。
rxjsにはすでにこれらのツールがあるため、await/asyncは使用しないでください.2つの方法を混在させないでください。

export class ParentComponent{ 
    // Step 2: handler start 
    handleChildEvent(execStep5) { 
    // this.longTimeMethod return Observable<void> 
    this.myService.longTimeMethod() 
     .map(() => { 
     // Step 3: Method executing finished 
     return Observable.of('done'); 
     }) 
     .subscribe(() => { 
     // Step 4: Another code 
     execStep5(); 
     }); 
    } 
} 

これを行うにはさらに短いコードがありますが、これはうまくいくはずです。

+0

お返事ありがとうございます。これは私の場合に役立ちます。 – x666ep

1

私はこのソリューションを同様の状況で試しましたが、まったく同じではありません。あなたの問題は今や順番になっていないのでステップ5にしかないので、ステップ5を0 waitでsetTimeout関数でラップすることができます。これにより、ステップ5がスケジュールされたタスクになります。

setTimeout(_ => {/*step 5 code*/}); 
関連する問題