私はノードとエクスプレスAPIのバックエンドを持つ角度2の電子商取引アプリケーションで作業しています。私は現在、私がpassport-facebookとjwtを認証に使用しているソーシャルログインセクションに取り組んでいます。私のコードの関心事はAngular 2の部分を中心に回転します。ユーザがfacebookボタンでログイン/登録をクリックすると、facebookログインフローを開始する新しいタブが開きます。そのウィンドウはwindow.postMessageを介してオープナーにjwtを返します。オープナーは、ウィンドウに成功メッセージを送り、開いたウィンドウが閉じます。すべて正常に動作しますが、非常にクリーンではありません。つまり、動作させるためにハックアップする必要がありました。理想的には、コンポーネントのすべてを処理するのではなく、facebookログインを処理するために私の認証サービスに電話するのが理想的ですが、window.postMessageのイベントハンドラの中では 'this'はコンポーネントを参照しません。 'this'経由のサービス。私はコンポーネントへの参照を取得する方法を把握することができないので、私はサービスを呼び出すことができます。誰にも何か提案はありますか?角2 window.postmessage
下記のログインコンポーネントがtypescriptです。必要に応じて他のコードを含めることができますが、必要があるかどうかわかりません。
import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
import { ILoginUser } from './loginUser.model';
@Component({
moduleId: module.id,
templateUrl: 'login.component.html',
styleUrls: ['login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private _authService: AuthService, private _router: Router) {
if (window.addEventListener) {
window.addEventListener("message", this.receiveMessage, false);
} else {
(<any>window).attachEvent("onmessage", this.receiveMessage);
}
}
ngOnInit() { }
user: ILoginUser = {
username: "",
password: ""
}
error: boolean = false;
success: boolean = false;
errorMessage: string = "";
redirect: boolean = false;
login() {
this._authService.login(this.user).subscribe(data => {
console.log (data);
if (data.success){
this._router.navigate(['/product']);
} else {
this.error = true,
this.errorMessage = data.message
}
}, errorMsg => {
this.error = true;
this.errorMessage = errorMsg;
});
}
receiveMessage(event: any)
{
if (event.origin !== "http://localhost:3000")
return;
localStorage.setItem("token", event.data.token);
localStorage.setItem("username", event.data.username);
(<any>window).popup.postMessage("success", "http://localhost:3000");
}
ngAfterViewChecked() {
//since we can't call the authservice directly we check to see if a redirect flag is set to true
if (this.redirect) {
this._router.navigate(['/product']);
}
}
authFacebook() {
(<any>window).popup = window.open('http://localhost:3000/api/auth/facebook');
//set the redirect flag to true so when angular checks again we can redirect to the products page
this.redirect = true;
}
}
これは完全に機能しました。どうもありがとうございます! – user3064073
角度の 'renderer'クラスでイベントリスナーを追加することもできます。 参照:http://stackoverflow.com/a/35082441/1762493 – Mikeumus