Angular 2 window.postmessage [英] Angular 2 window.postmessage

查看:495
本文介绍了Angular 2 window.postmessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Angular 2中使用一个节点开发一个电子商务应用程序,并表达api后端.我目前正在使用"password-facebook"和"jwt"进行身份验证的社交登录"部分.我的代码涉及到围绕Angular 2部分.当用户单击使用Facebook登录/注册"按钮时,它将打开一个新标签,该标签开始Facebook登录流程.然后,该窗口将通过window.postMessage将jwt返回给打开器.然后,打开程序将成功消息发送给窗口,并且打开的窗口将关闭.一切正常,但不是很干净,即我必须对其进行破解才能使其正常工作.理想情况下,我将调用授权服务来处理facebook登录,而不是处理组件中的所有内容,而是处理window的事件处理程序中的所有内容.postMessage'this'不再引用组件,而是引用窗口对象,因此我无法调用通过"this"提供服务.我不知道如何获得对该组件的引用,因此可以调用该服务.有人有什么建议吗?

I'm working on an eCommerce application in Angular 2 with a node and express api backend. I'm currently working on the social login section where I am using passport-facebook and jwt for authentication. My code concerns revolve around the Angular 2 portion. When a user clicks on the login/register with facebook button it opens a new tab that begins the facebook login flow. That window will then return the jwt to the opener via window.postMessage. The opener then sends the window a success message and the opened window will close. Everything works correctly but it's not very clean, i.e. I had to hack it up to make it work. Ideally I would call my authorization service to handle the facebook login instead of handling everything in my component but inside the event handler for the window.postMessage 'this' no longer references the component, it references the window object so I can't call the service via 'this'. I can't figure out how to get a reference to the component so I can call the service. Does anyone have any suggestions?

以下是我在打字稿中的登录组件.如果需要,我可以包含其他代码,但我不知道这是必需的.

Below is my login component in typescript. I can include other code if need be but I don't know that it is needed.

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

推荐答案

您应更改声明eventListener的方式(通过使用bind(this)或匿名函数,或更改声明eventHandlers的方式:

You should change the way you declare the eventListener (by using bind(this) or an anonymous function, or change the way you declare your eventHandlers:

绑定(this):

constructor(private _authService: AuthService, private _router: Router) { 
   if (window.addEventListener) {
     window.addEventListener("message", this.receiveMessage.bind(this), false);
   } else {
      (<any>window).attachEvent("onmessage", this.receiveMessage.bind(this));
   }
}

匿名函数

window.addEventListener("message", () => {
   this.receiveMessage();
}, false)

eventHandler的不同声明

receiveMessage: any = (event: any) =>  {
  //...
}

选择:)使用最后一个选项,可以很容易地分离eventListener

Take your pick :) With the last option it is easy to detach the eventListener

这篇关于Angular 2 window.postmessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆