Sáv*_*res 2 javascript routes angular
我在一个组件中有一个对象,我想将它传递给另一个组件。问题是这个其他组件将在新选项卡中打开。
我试图使用数据服务策略,但是当标签打开时,数据服务对象未定义。
我考虑过使用查询参数并传入 url。但是对象很复杂
我的数据服务:
@Injectable({providedIn: 'root'})
export class DataService {
private anime: Anime;
constructor() { }
setAnime(anime: Anime) {
this.anime = anime;
}
getAnime() {
return this.anime;
}
}
Run Code Online (Sandbox Code Playgroud)
在数据服务中设置对象:
goToDetailsByService(anime: Anime) {
this.dataService.setAnime(anime);
//this.router.navigateByUrl('/details');
window.open('/details');
}
Run Code Online (Sandbox Code Playgroud)
通过服务数据获取动漫对象:
ngOnInit(): void {
console.log(this.dataService.getAnime());
this.anime = this.dataService.getAnime()
}
Run Code Online (Sandbox Code Playgroud)
通过导航路由器访问详细信息组件时
I think there are two ways to do it. The first one is localStorage , the second one is PostMessage
我们可以使用 localstorage 因为可以跨窗口读取存储,并且当您向存储写入内容时会触发存储事件。
这是代码示例。
// parent window
localStorage.setItem("EVENT.PUB", JSON.stringify(anime));
// child widnow
window.addEventListener('storage', function(event) {
console.log(event);
const anime = JSON.parse(event.newValue);
}, false);
Run Code Online (Sandbox Code Playgroud)
该window.postMessage()方法可以安全地启用 Window 对象之间的通信;例如,在页面和它产生的弹出窗口之间,或在页面和嵌入其中的 iframe 之间。
这是代码示例。
// parent window
const detailPage = window.open('/details');
detailPage.postMessage(anime, '*');
// important notice: anime should be object that can be serialize
// otherwise error will happen when execute this function.
// child window
window.addEventListener('message', (event) => {
// get out the message
console.log(event.data);
// and you can even send message back to parent window too.
event.source.postMessage('Got it!', event.origin);
}, false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4629 次 |
| 最近记录: |