2017-05-14 5 views
0

AuthService가 있고 LoginComponent에서 signInAction 메서드를 호출하고 있습니다. 토큰이 초기화 될 때 리디렉션하고 싶습니다.서비스가 Angular 4 애플리케이션에서 작업을 완료하면 리디렉션하려고합니다.

어떻게하면됩니까? 여기

내 auth.service.ts 여기
signInAction(){ 
     let that = this; 
     new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) { 
      that.currentUser = user; 
      that.token = user.access_token; 
     }).catch(function (e) { 
      console.error(e); 
     }); 
     } 

내 LoginComponent 파일

ngOnInit() { 
    this.authService.signInAction(); 
    //Wait until signInAction is complete before navigateByUrl 
    this.router.navigateByUrl('/my-profile'); 
    } 

/업데이트] WORKING 버전 모두에/ 감사 인 파일에서 로그인의 방법, 내가 배운 Observable이 어떻게 작동하는지 그리고 이것이 나의 최종 작업 버전입니다. 내 LoginComponent에서 AuthService

signInAction(){ 
    let that = this; 
    return Observable.create(observer => 
     new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) { 
      that.currentUser = user; 
      that.token = user.access_token; 
      observer.next(); 
      observer.complete(); 
     }).catch(function (e) { 
      console.error(e); 
      observer.complete(); 
     }) 
    ); 
    } 

//에서

//

ngOnInit() { 
    this.authService.signInAction() 
     .subscribe(
     () => this.router.navigateByUrl('/my-profile') 
    ); 
    } 
+1

현재 작성한대로 할 수 없습니다. 프로세스가 완료되면 외부에서 알 수있는 방법이 없습니다. 'signInAction'에서 관찰 할 수있는 것을 반환 할 수 있습니다. 'this.authService.signInAction(). subscribe (() => this.router.navigateByUrl ('/ my-profile '))'). 또는 관찰 완료 가능한 이벤트를 통해 프로세스 완료를 노출합니다. 'this.authService.signInAction(); this.authService.signedIn $ .subscribe (...); ' – jonrsharpe

답변

0

할 일이 더 나은 방법이있을 수 있습니다. 서비스 클래스에서

import { EventEmitter } from '@angular/core';

이벤트 이미 터를 정의하고 토큰 업데이트 후 이벤트를 방출 : 다음

tokenUpdated = new EventEmitter<void>(); 

    signInAction() { 
    let that = this; 
    new Oidc.UserManager(this.config).signinRedirectCallback().then(function (user) { 
     that.currentUser = user; 
     that.token = user.access_token; 
     that.tokenUpdated.emit(); 
    }).catch(function (e) { 
     console.error(e); 
    }); 
    } 

, 당신은 EventEmitter를 사용하여 구성 요소에 가입, 지금은이 문제를 해결할 수 있습니다 귀하의 구성 요소에 귀하가 가입 할 수 있습니다 :

ngOnInit() { 
    this.authService.signInAction(); 
    //Wait until signInAction is complete before navigateByUrl 
    this.authService.tokenUpdated 
     .subscribe(
     () => this.router.navigateByUrl('/my-profile') 
    ); 
    } 
0

나는 관측 가능 물을 사용하겠다는 모든 답변에 동의합니다. 당신이 일해야하는 것을 얻기의 목적, 당신은 간단한 콜백을 사용할 수 있습니다.

this.authService.signInAction((user) => { 
    this.router.navigateByUrl('/my-profile'); 
}); 

// --- 

signInAction(next){ 
    let that = this; 
    new Oidc.UserManager(this.config) 
     .signinRedirectCallback() 
     .then(function (user) { 
      that.currentUser = user; 
      that.token = user.access_token; 
      next(user); 
+0

이 솔루션은 정말 잘 작동하지만, 나는 eventImitter를 꽤 좋아합니다. 솔루션 주셔서 감사합니다. –