Engage with a feature that is currently displayed in a separate window

I'm working on a project that requires me to display 2 different components in separate browser windows. I've tried opening two windows and displaying the components, but now I'm wondering if there's a way for a component in one window to interact with another component in the second window.

I attempted to create a Subject in a Service, but when I try to subscribe to this Subject in the component of the other window, it doesn't seem to work. Here is an example of what I have done:

export class MyService {
  public navigationTrigger: Subject<NavigationParams> = new Subject();

  constructor(private _http: Http) {
    this.navigationTrigger.next(params);
  }
}

And in the component, I subscribe to it like this:

this.watsonService.navigationTrigger.subscribe((navigation) => {
   this.updateNavigation(navigation); 
});

Unfortunately, this approach does not seem to be achieving the desired result. I am still unsure how to proceed in order to make this interaction between components in separate windows possible.

Answer №1

When it comes to real-time communication, using a Subject may not be the best option as it is limited to a single Window's scope.

For effective communication between two different users, WebSockets would be more suitable. However, if it involves the same user, localStorage can be utilized.

Sending Data:

    localStorage.setItem("someKey", "someValue");

Receiving Data:

    window.addEventListener('storage', storageEventHandler, false);

    function storageEventHandler(evt) {
        alert("storage event called key: " + evt.key);
    }

To enhance this process further, you can encapsulate it within an Observable. Here's an example for reference:

    Rx.Observable.create(observer => {
     window.addEventListener('storage', storageEventHandler, false);

     function storageEventHandler(evt) {
         alert("storage event called key: " + evt.key);
         observer.onNext(evt);
     }
     // todo: return unsubscribe function which will remove that eventListener

});

Answer №2

David's answer above is effective, especially considering Angular 2's versatility in running on various platforms beyond just web browsers. In cases where objects like window are not readily available, it's recommended to wrap them and inject them using dependency injection. This allows for flexibility in changing the object instance based on the application environment.

import { WindowRef } from './WindowRef';
@Component({...})
class MyComponent {
    constructor(private winRef: WindowRef) {
        // accessing the native window object
        console.log('Native window object:', winRef.nativeWindow);
     }
}

To wrap window in an Angular 2 service, a simple solution involves creating an ES6 class and annotating it with @Injectable.

import { Injectable } from '@angular/core';
function _window() : any {
   // accessing the global browser window object
   return window;
}
@Injectable()
export class WindowRef {
   get nativeWindow() : any {
      return _window();
   }
}

Don't forget to register WindowRef as a provider:

 @NgModule({
    ...
    providers: [ WindowRef ]
 })
 export class AppModule{}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on altering button color when input field is populated

I have been researching online and have not come across any discussions on how to dynamically change the color of a button in JavaScript when an input field is filled. I haven't really tried any code myself because there are very limited resources add ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Issue with Chrome Extension's Local Storage Functionality is Causing Errors

Currently, I am in the process of developing a Chrome extension that utilizes a content script to make modifications on specific sections of a website. Everything was functioning smoothly until I decided to incorporate an options page into my extension. M ...

Several components within the same lazy route are malfunctioning

Query - Is it possible to have multiple routes that point to the same lazy loaded module (and its associated router)? I keep encountering the error message "Error: Cannot match any routes: 'Page30'". Below is my app.routing.ts file where the laz ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Angular Reacts to Pre-Flight Inquiry

I'm facing an issue with my interceptor that manages requests on my controllers. The back-end web API has a refresh token implementation, but when I try to refresh my token and proceed with the request, I encounter the error message "Response to prefl ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Capturing the mouse's idle state within a Master Page iFrame using JavaScript

Currently, I have a website set up with a Master page that displays various other pages from different folders in an IFrame within the master page. My goal is to implement a feature where if the user remains inactive on any of these pages for a certain p ...

How can holidays be incorporated into the Kendo UI scheduler in Angular 6?

Is there a way to incorporate holidays into the Kendo UI scheduler in an Angular 6 project? I have a JSON array containing holiday dates, and during holidays I want to restrict users from adding events. Additionally, I would like the background color to b ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

Tips for implementing Header Authorization on a POST FORM with JS/AJAX/JQUERY

Looking to gather user inputs through a form on my webpage and send those values to a PHP hosted on an external site. The Request maker extension indicates that the Header Authorization is included along with other inputs when data is submitted to the exte ...

Tips for updating the URL in the browser address bar after loading content using AJAX with angular.js

When developing a web application using angular.js, the communication within the app is done through AJAX. This means that when the application requests web resources, the URL in the browser address bar does not change. For instance, my app displays build ...

Preserve component state in Angular 4 by saving it when navigating to a different component

Currently, I am faced with a challenge while developing an application using Angular. In one component, users can input data into three selectboxes and then initiate a search to find matching results. Upon clicking on a match, they are taken to another com ...

Accessing observable property in Angular 2 with TypeScript: A comprehensive guide

My observable is populated in the following manner: this._mySubscription = this._myService.fetchData(id) .subscribe( response => this._myData = response, ...

What are the best strategies for eliminating element cloning and duplication in Vue?

As a novice programmer, I've developed a web app similar to Trello. It allows users to create boards and within those boards, lists can be created. Each list is displayed uniquely with different IDs. However, the list items are displayed with the same ...

discovering the category for the .click function

After retrieving a list of book objects from a JSON object, I am in the process of displaying them on an HTML page by creating buttons with titles. The goal is to alert the URL of the book when a button is clicked. However, I am facing an issue with access ...

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...

Having trouble with my Express app due to errors popping up because of the order of my routes

app.get('/campgrounds/:id/edit', async (req,res) =>{ const campground = await Campground.findById(req.params.id) res.render('campgrounds/edit', { campground }); }) app.get('/campgrounds/:id', async (req,res) =>{ ...

What could be causing my function to fail <object>?

Within index.php, I am calling the function twice, which includes chart.html. index.php chart_line($valuesNight); //first call chart_line($valuesEvening); //second call ?> <?php function chart_line($jsonDataSource){ ?> < ...