The ngxUX Window Receiver Module allows you to easily expose external methods to the window
object and observe method calls using subscriptions.
Install the node module with npm:
terminal command$ npm install @ngxux/window-receiver
We need to add the NgxuxWindowReceiver
module to our app.module.ts
imports:
app.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { NgxuxWindowReceiverModule } from '@ngxux/window-receiver';import { AppComponent } from './app.component';@NgModule({declarations: [AppComponent],imports: [BrowserModule,NgxuxWindowReceiverModule],providers: [],bootstrap: [ AppComponent ]})export class AppModule {}
You register your external functions by calling the NgxuxWindowReceiverService.add(..)
method. This method will register your external function by name and returns an Observable
which you can subscribe to anywhere, anytime.
Before we can use external methods we need to inject the service. You do this by passing the following variable to your class constructor like so:
app.component.tsexport class AppComponent {public constructor(private windowReceiverService: NgxuxWindowReceiverService) {...}}
Call the .add(..)
method on the NgxuxWindowReceiverService
passing an object with the property methodName
which will become the external method exposed to window
app.component.tsthis.windowReceiverService.add({methodName: 'myExternalFunction'}).subscribe(args => {console.log('myExternalFunction called with arguments:', args);});
Patching things together we:
Include NgxuxWindowReceiverModule
in our app.module.ts
class.
Inject NgxuxWindowReceiverService
in our app.component.ts
class.
We add our external methods to the service by calling .add(..)
.
app.component.tsimport { Component } from '@angular/core';import { NgxuxWindowReceiverService } from '@ngxux/window-receiver';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: [ './app.component.scss' ]})export class AppComponent {/*** Inject the window reicever service.** @param {NgxuxWindowReceiverService} windowReceiverService*/public constructor(private windowReceiverService: NgxuxWindowReceiverService) {//// Add the external function by name and subscribe to the observable// that is returned.//this.windowReceiverService.add({methodName: 'myExternalFunction'}).subscribe(args => {console.log('myExternalFunction called with arguments:', args);});}}
Now we can call the javascript function myExternalFunction('Hello World!!');
externally. Give it a try in your web browsers developer console!
You can add and remove methods at any time during runtime. Use the tearDown()
method to remove all methods. Removing a method will also unsubscribe your subscriptions.
Method Name | Arguments |
add |
|
remove |
|
tearDown | none |
Join us on our discord server at https://discord.gg/programming.