2017-05-14 15 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'); 
    } 

/UPDATED 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

行うには良いアプローチがあるかもしれません。しかし、あなたが持つEventEmitterを使用し、コンポーネントにそれに加入し、今のところ、この問題を解決することができます:

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); 
    }); 
    } 

その後、 、あなたのコンポーネントでは、あなたはそれを購読することができます。

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がかなり好きです。あなたのソリューションに感謝します –

関連する問題