在我当前的项目中,我有多个 Angular 2 应用程序,它们应该由门户应用程序(也是 Angular 2)提供服务。因此门户应用程序有一个标题区域,其中包含指向所有底层应用程序的链接。当用户单击一个应用程序链接时,相应的 Angular 2 应用程序将加载到门户主体的 iframe 中。
现在我开发了一个中央授权服务。在门户中,我有一个服务,它拥有当前登录用户的权限。我的问题是:是否可以在单个应用程序(iframe)中访问父级(门户)的 Angular 2 服务/组件? Angular 1 似乎是可能的 via scope
最佳答案
我目前正在考虑做类似的事情(在 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');
在客户端应用程序上(托管在 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');
}
}
在父级中显示子框架路由 因此,在我的实现中,我们将 token 和用户信息从 shell 应用程序传递到子 iFrame,并将路由信息从子应用程序传递回 shell,以便 url 反射(reflect)在子应用程序中选择的路由。 在子应用程序中,您可能有一条路线,例如:
[userapp]/edituser/username
,我们希望将其发布到父应用程序并显示如下路线:
请注意,我们使用 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},'*')
}
})
}
然后在父应用程序中解析消息并使用它来更新显示的位置路径。
url = url +'#' + route;
this.location.go(url);
关于javascript - Angular 2 iframe与父通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41674712/