2017-12-06 11 views
0

ログイン後、authserviceが呼び出され、ルーティングがprofilecomponentに対して機能します。angular 5 post request returns 2回返信

投稿リクエストは2回送信されていますが、私はCorsを使用していないので、これは事前に照会されたリクエストではないと仮定していますか? Profile.component.ts ngoninitは2回実行されているようですが、最初に正しいidでcoinIdを受け取り、続いて定義されていないcoinIdを受け取ります。

5a273e34f5c5643e18c035dacoinId from profile2! 
    main.f2eaf663cdbf963d2af8.bundle.js:1 undefinedcoinId from profile2! 

私はnginxのサーバーが、それはこの問題を解決するだろうかどうかわからないが開始考えています、このすべてに非常に新しいです。

login.component.ts

let url = 'http://localhost:3000/api/login'; 
    this.newService.login(url, user, user.username).subscribe(result => { 

var value = result["user"]; 
var coinId = result.user.coinid; 
this.router.navigate(['/profile', coinId]); 

auth.service.ts

login(url: string, user: any, username: any) 
    {return this.http.post(url , user) 
    .do (res => this.setSession(res)) 
    } 

    private setSession(authResult) { 

     const expiresAt = moment().add(authResult.expiresIn,'second'); 
     this.loggedIn.next(!!localStorage.getItem('id_token')); 

     console.log(authResult.token + "dit is de token"); 
     localStorage.setItem('id_token', authResult.idToken); 

     localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf())); 

    }  

profile.component.ts

ngOnInit() { 
    var coinId = this.route.snapshot.params['id']; 
console.log(coinId + "coinId from profile2!") 


    this.router.navigate([ '/profile', {outlets: { formOutlet: 
    ['profileform', coinAId]}}]); 
    } 

答えて

0

I Angularの新機能ですが、shareReplay()を使用すると、POSTリクエストのマルチキャストを避けることができます。 RxSwiftは、同じObservableへの複数のサブスクリプションを持ち、サブスクリプションのコードが再び再実行されないようにするために、別の演算子を提供します。&またはサブスクリプションが期限切れになるまで。使用できる演算子は、replay()、replayAll()、publish()、share()、およびshareReplay()です。

は、以下のようにコードを変更してください:

login(url: string, user: any, username: any) 
    {return this.http.post(url , user) 
    .do (res => this.setSession(res)) 
    .shareReplay() 
    } 

shareReplay()は、単一のサブスクリプションを保証します。 shareReplayは、それらのイベントが送信されると、観測者から観測者のイベントを再生します。ドキュメントごとに:

再生バッファの最大時間の長さに従った通知を再生する、基本シーケンスとの単一サブスクリプションを共有する観測可能シーケンスを返します。このオペレータは、観察者の数が から0になるときに接続可能な観察可能なシーケンス に接続するリプレイの特殊化であり、オブザーバがなくなったときに切断されます。

Github Docs & Example

Also See this question on Stackoverflow with simplified explanation