javascript - 在新选项卡中的组件之间传递数据

标签 javascript angular routes

我在一个组件中有一个对象,我想将其传递给另一个组件。问题是这个其他组件将在新选项卡中打开。

我尝试使用数据服务策略,但是当选项卡打开时,数据服务对象未定义。

我考虑过使用查询参数并传入 url。但对象非常复杂

我的数据服务:

  @Injectable({providedIn: 'root'})
  export class DataService {

   private anime: Anime;

   constructor() { }

   setAnime(anime: Anime) {
    this.anime = anime;
   }
   getAnime() {
    return this.anime;
   }
 }

在数据服务中设置对象:

goToDetailsByService(anime: Anime) {
   this.dataService.setAnime(anime);
   //this.router.navigateByUrl('/details');
   window.open('/details');
}

通过服务数据获取动漫对象:

ngOnInit(): void {
  console.log(this.dataService.getAnime());
  this.anime = this.dataService.getAnime()

}

通过导航路由器访问详细信息组件时有效

最佳答案

我认为有两种方法可以做到这一点。第一个是localStorage ,第二个是 PostMessage

本地存储

我们可以使用本地存储,因为存储可以跨窗口读取,并且当您向存储写入内容时会触发存储事件。

这是代码示例。

// 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);

发布消息

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);

关于javascript - 在新选项卡中的组件之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503980/

相关文章:

angular - 如何从组件更改片段

php - Zend Framework 3 - 基于查询字符串的路由

javascript - window.setTimeout 的条件问题

javascript - 使用 JavaScript 将 JSON 转换为 html 表标记

Angular 2 CLI 这么多时间编译

angular - 如何使用@HostListener 检测滚动条是否存在

node.js - 在 ExpressJS 中将参数从路由器传递到 Controller

javascript - 如何在node/mean/express应用程序中拆分index.js文件?

javascript - Cordova 3.5 的 InAppbrowser window.open 插件无法正常工作

javascript - 隐藏图像/背景颜色下方的文本