2017-08-01 3 views
2

httpを呼び出し、Observableをユーザーの詳細で返す関数があるとします。エラーを出すObservableを呼び出す方法

ユーザーが存在しない場合、エラーを出力するObservableを返します。

// Get user by id 
function getUser(id) { 
    return Rx.Observable.create(obs => { 
    if (id === 1) { 
     obs.next('200 - User found'); 
     obs.complete(); 
    } else { 
     obs.error('404 - User not found'); 
    } 
    }); 
} 

// This will print "200 - User found" in the console after 2 seconds 
getUser(1) 
    .delay(2000) 
    .subscribe(r => console.log(r)); 

// !!! Delay will not work here because error emmited 
getUser(2) 
    .delay(2000) 
    .subscribe(null, e => console.log(e)); 

エラーを発する観察可能遅延する方法はありますか?

+0

なぜそれを遅らせますか? –

+0

成功してもなくても(応答が長すぎるとアプリがどのように動作するかをテストするために)APIのすべてのhttpリクエストを遅らせたい場合 –

+1

テストを書いていますか?あなたは通常、長い要求をエミュレートするブラウザのネットワークタブ抑制機能を使用する必要があります –

答えて

1

私は好奇心が強い、それはここでエラー

を返した場合、なぜ観察可能な遅れはありませんがdelayオペレータのソースコードです:ただ、他のすべての演算子と同じように

class DelaySubscriber<T> extends Subscriber<T> { 
    ... 

    protected _next(value: T) { 
    this.scheduleNotification(Notification.createNext(value)); <-------- notification is scheduled 
    } 

    protected _error(err: any) { 
    this.errored = true; 
    this.queue = []; 
    this.destination.error(err); <-------- error is triggered immediately 
    } 

    protected _complete() { 
    this.scheduleNotification(Notification.createComplete()); 
    } 
} 

delayはあなたのケースではソースストリーム - getUser()を購読し、リスナーに通知します。ソースコードから、エラーが発生したときに通知をスケジュールしないで、すぐにオブザーバブルのerrorメソッドをトリガすることがわかります。

私は関係なく、成功、それか APIへのすべてのHTTP要求をしませ遅らせたい(応答が長すぎるアプリがどのように動作するかをテストするために)

私はクロームデバッグのthrottle機能を使用することをお勧めしますツール(ネットワークタブ)。

関連する問題