我想在父级和子级标签之间进行通信。我将在子选项卡(不同的组件然后是父组件)中获取一些数据,然后将此数据发送给父组件。 我认为使用浏览器本地存储是正确的方法。因此,我将数据插入到localstorage,并希望该父组件自动吸收此更改,从localstorage获取数据并关闭子窗口。
我有两个用于父窗口和子窗口的组件,以及一个用于订阅本地存储的服务。问题是父组件没有看到更改,因为我正在更改子组件中的“下一个”主题。
服务代码为:
export class ObserveLocalStorageService {
private storageSub= new Subject<any>();
watchStorage(): Observable<any> {
return this.storageSub.asObservable();
}
setItem(key: string, data: any) {
localStorage.setItem(key, data);
this.storageSub.next('changed');
}
removeItem(key) {
localStorage.removeItem(key);
this.storageSub.next('changed');
}
}
子组件代码为:
export class FbLoginPopupComponent implements OnInit {
uriObject: any;
constructor(private storageService: ObserveLocalStorageService,
private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.fragment.subscribe((fragment: string) => {
console.log('My hash fragment is here => ', fragment);
this.uriObject = JSON.parse('{"' + decodeURI(fragment)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g,'":"') + '"}');
if (this.uriObject['access_token']) {
this.storageService.setItem('fb_tk', true);
this.storageService.setItem('fb_tk_is', this.uriObject['access_token']);
} else {
this.storageService.setItem('fb_tk_err', this.uriObject['error']);
this.storageService.setItem('fb_tk_err_desc', this.uriObject['error_description']);
}
}
}
最后,我的父组件看起来像:
export class FacebookLoginComponent implements OnInit, OnDestroy {
private authWindow: Window;
constructor(private storageService: ObserveLocalStorageService) {}
ngOnInit() {
this.storageService.watchStorage().subscribe((data: string) => {
console.log(data); <------------------ **problem is here. data is not loging**
});
launchFbLogin() {
this.authWindow = window.open('https://www.facebook.com/v2.11/dialog/oauth?' +
'&response_type=token' +
'&display=popup' +
'&client_id=123321123321123321123321' +
'&display=popup' +
'&redirect_uri=https://localhost:44312/auth/fb-login-popup' +
// '&redirect_uri=https://localhost:44312/facebook-auth.html' +
'&scope=email',null,'width=600,height=400');
}
}
我找不到解决方案。请帮忙。
谢谢