2017-12-06 3 views
0

로그인 한 후 authservice가 호출 된 다음 라우팅이 profilecomponent에 적용됩니다.angular 5 post request returns 두 번 반환

그러나 게시 요청이 두 번 전송되는 중이므로 Cors를 사용하지 않아서 미리 요청 된 요청이 될 수 없다고 가정합니다. Profile.component.ts ngoninit가 두 번 실행되는 것 같습니다. 정확한 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