Angular 2 iframe与父通信

JuH*_*m89 20 javascript iframe angular

在我目前的项目中,我有多个Angular 2应用程序,应该由门户应用程序(也是Angular 2)提供服务.因此,门户网站应用程序的标题区域包含指向所有底层应用程序的链 当用户点击一个应用程序链接时,相应的角度2应用程序将加载到门户主体的iframe中.

在此输入图像描述

现在我开发了一个中央授权服务.在门户网站中,我有一个服务,它拥有当前登录用户的权限.我的问题是:是否可以在单个应用程序(iframe)中访问父(门户)的角度2服务/组件?它似乎可能在角度1 范围内

jaz*_*000 11

我正在寻找类似的东西(在iFrame中使用子应用程序的门户应用程序)您可以使用window.postMessage发送数据,在服务器和客户端之间(在任一方向上)进行通信.

例如,在服务器应用程序上:

var iframe = document.getElementById('useriframe');
    if (iframe == null) return;
    var iWindow = (<HTMLIFrameElement>iframe).contentWindow;

    iWindow.postMessage({"for":"user","data":"anything"}, 'http://localhost:4001');
Run Code Online (Sandbox Code Playgroud)

并在客户端应用程序上(在iFrame中托管)

export class AppComponent {

@HostListener('window:message',['$event'])
onMessage(e)
{
if (e.origin!="http://localhost:4200")
  {
  return false;
  }
if (e.data.for=="user")
  {
  alert('here i am');
  }
}
Run Code Online (Sandbox Code Playgroud)

在父级中显示子帧路由 因此,在我的实现中,我们将shell应用程序中的标记和用户信息传递给子iFrame,并将子应用程序中的路由信息​​传递回shell,以便url反映在儿童申请.在子应用程序中,您可能有以下路线:

[userapp]/edituser /用户名

,我们希望将其发布到父应用程序并显示如下路线:

HTTP:// mywebsite /主/应用/用户#edituser /鲍勃

请注意,我们使用hashtag标记子路由,并在您的子应用程序中拦截每个导航事件并通过其发布新路由

export class MyRoutingComponent implements OnInit {
constructor(private router: Router) { 
router.events.subscribe((event: Event)=>{
  if (event instanceof NavigationEnd){
        let url=(<NavigationEnd>event).url;
        if (url.length>1)//don't post message about base route '/'
          window.parent.postMessage({"for":"dashboard", "operation":"changeroute","route":url},'*')
  }

})
}
Run Code Online (Sandbox Code Playgroud)

然后在父应用程序中解析消息并使用它来更新显示的位置路径.

    url = url +'#' + route;            
    this.location.go(url);
Run Code Online (Sandbox Code Playgroud)


Ame*_*eya 5

您好,非常感谢@ jazza1000提供的解决方案,它对我有所帮助。

我们的问题是在目前(迄今为止)的 Angular cli版本中存在一个错误,即使使用allowJs,该错误也无法使用外部JS文件。我们将使用jsplumb(外部js)表示一些流程图。(堆栈溢出的实际问题

因此,我们决定采用在其他angular 4应用程序中托管使用​​外部JS的功能的方法。父angular 5应用程序将通过iFrame引入angular 4应用程序。因此,当用户想要查看流程图时,我们将在iframe中打开angular4应用程序,然后他将在完成操作后单击“ angular 4”应用程序中的“保存”,该操作将保存所有修改,然后将消息发送到将关闭/隐藏的父窗口使用iframe的div。

我们在angular 5中的父应用程序具有以下代码

 @HostListener('window:message', ['$event'])
  onMessage(e) {
    debugger;
    if (e.origin != "http://localhost:4201") { // set your origin
      return false;
    }
    if (e.data.for == "user") {
      alert('here i am');
    }
  }
Run Code Online (Sandbox Code Playgroud)

我们保存按钮上的iFrame angular 4应用程序具有代码(我们使用--port 4201启动该应用程序)

window.parent.window.postMessage({"for":"user","data":"anything"}, 'http://localhost:4200')
Run Code Online (Sandbox Code Playgroud)