需求:有A和B两个页面。
B页面为A页面中点击后新建出的页面,方法为window.open()。
当B页面创建一个数据对象后,要把这个数据对象及时传递给A页面。
解决思路:
将要通信的数据存到localStorage中,创建一个service去定时查询localStorage是否有数据。
B页面在合适的时机向localStorage中写入数据。
service查询到localStorage有数据写入后把数据拿到,然后发送一个abp.event事件,A页面监听该abp.event事件,以拿到的数据。
1,A页面点击打开B页面
// A页面
url = './app/home';
window.open(url, '_blank',
'toolbar=no, location=no, directories=no, status=no, ' +
'menubar=no, scrollbars=yes, resizable=no, width=1282, height=1000'
);
2,service服务查询localStorage数据。
import { Injectable } from '@angular/core';
@Injectable()
export class CheckLocalstoragechangeService {
constructor() {
console.log('CheckLocalstoragechangeService constructor');
this.checkAddObjectFunction('addObject');
}
checkAddObjectFunction(objectTypeString: string): void {
setInterval(function() {
const json = localStorage.getItem(objectTypeString);
if (json !== undefined && json !== null) {
const object = JSON.parse(json);
abp.event.trigger(objectTypeString, object );
localStorage.removeItem(objectTypeString);
}
}, 1000);
}
}
将service添加到Module中。(每个项目的结构ngModule不同,注入服务的方式也不同,一般可选择将服务注入到AppModule或者在服务中使用@Injectable({ providedIn: 'root', }。若服务不生效请具体查询angular的ngModule和服务依赖注入的相关文档)
@NgModule({
providers: [
CheckLocalstoragechangeService ,
]
})
export class ServiceProxyModule { }
3,B页面向localStorage添加数据
localStorage.setItem('addObject', JSON.stringify(object));
4,A页面注册监听abp.event事件,在applyObject()方法中去应用该对象。
ngOnInit() {
abp.event.on('addObject', object => this.applyObject(object));
}