Can Angular 5 integrate with Pusher?

Below is the javascript code used to integrate Pusher into native HTML:

<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>

// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('MY_PUSHER_KEY', {
  cluster: 'MY_CLUSTER',
  encrypted: true
});

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
  alert(data.message);
});

Now, I am looking to incorporate the above javascript code into one of my Angular components so they can subscribe to that channel. Any guidance on how to achieve this would be greatly appreciated. Thank you in advance!

Answer №1

If you are working with Angular 4, 5, or a newer version, you will need to use the JavaScript version of Pusher and integrate it into your project. Here is a straightforward example to help you get started: 1. Begin by installing Pusher in your Angular project:

npm install --save pusher-js

2. Next, open the .angular-cli.json file and add the following line to the "scripts" section:

"scripts": ["../node_modules/pusher-js/dist/web/pusher.min.js"]

3. To make this integration work, you'll need to make an HTTP request to your server. You can achieve this by creating a service using the Angular CLI or your preferred method:

ng g s my-service
  • Important:
         - Don't forget to register this service in app.module.ts. Additionally, ensure you have imported HttpClientModule or HttpModule, as one of them will be used in your service.

5. Within my-service.service.ts:
- Once you have imported the httpClient module, include the following statement to start using Pusher:

declare const Pusher: any;

6. Inside the constructor of My Service:

   this.pusher = new Pusher('YOUR_PUSHER_KEY', {
      cluster: 'YOUR_PUSHER_CLUSTER',
      encrypted: true
    });
    this.channel = this.pusher.subscribe('my-channel');

7. Create a function within the service to send a POST request to your server and trigger the event.
8. Once your service is set up, navigate to the component where you want the real-time functionality. First, inject your service in the constructor, and then bind to the channel for the specific event (in this case, "my-event"):

 ngOnInit() {
    this.myService.channel.bind('my-event', data => {
      this.message = data.message;
    });
  }

By following these steps, you can create a simple real-time application within your Angular 5 project!

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

Triggering the Vuetify select/autocomplete/combobox menu to open upon focusing on it

I'm working on implementing a Vuetifyjs Autocomplete feature. My goal is to have the menu open when the user focuses on it using the tab key after entering information in a previous input field. Below is a snippet of the code I am using: <div id=" ...

Tips for simulating an ajax request in a Jasmine test

Check out my code snippet below: function sendRequestData(url, urlParameters) { $.ajax({ url : url, method : 'POST', headers : { 'Accept' : 'application/json' }, contentType : 'application/js ...

Mastering the art of chaining HTTP requests with RxJS for optimal results

I have a task that involves making multiple HTTP calls sequentially, examining the result of each call before proceeding to the next one. Depending on the response, I may need to display a message, continue to the next call, or break the chain. Additionall ...

Error: An error occurred because the program attempted to read properties of a null value, specifically the property "defaultPrevented"

There seems to be an issue with a script error involving both the bootstrap alert and my own close alert tag. I have a script set up to automatically close alerts after 2.5 seconds when certain user actions trigger them, such as creating a blog post or del ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Add information if the data does not exist, modify it if it does

My current project involves creating a TS3 bot using the Node.js Library from Multivit4min on GitHub. The purpose of this bot is to perform the following tasks: nick (txt) cldbid (int) clid (txt) lastChannel (int) Event #1 - When a client connects to a ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

I must update the menu to show only one sub-menu at a time, ensuring that multiple menus cannot be displayed simultaneously

When I click on a menu option, it displays correctly, but when I click on another option, both are displayed. The goal is to only display one at a time. https://i.sstatic.net/J6vLf.png $('.sub-menu ul').hide(); $(".sub-menu a").click( ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

Can a repetitive 'setTimeout' function invocation ultimately cause the JS Engine to crash?

Imagine a scenario where I require data from the server every 10 seconds. A function would be created to fetch the data using AJAX, and then setTimeout would be used to schedule the function to run again: function RetrieveData(){ $.ajax({ url: " ...

Encountering a hydration issue with an SVG element embedded within a Link component in Next

I'm encountering a hydration error related to an icon within a link, Here is the error message: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <svg ...

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

Is there a way to access multiple values from my function array in Javascript instead of just the first one?

function findDistinctElements(inputArray) { let distinctItems = []; for (let i = 0; i < inputArray.length; i++) { const currentItem = inputArray[i]; if (!distinctItems.includes(currentItem)) { console.log(`Argument ${i+1}: $ ...

I have to create a duplicate for the clipboard containing a dynamic variable in Angular

CSS Note: The Technical.url variable in the specification is constantly changing, and every time I click the button, I want to copy the URL. <div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="" ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Collision detection in Physisjs with Three.js PointerLockControls is an essential feature for creating

I am currently working on a project using Three.js with PointerLockControls. My goal is to implement collision detection for the player in order to enhance the overall experience. To achieve this, I have created a new Physijs cylinder object and passed it ...

The FileReader.result is found to be null

Currently, I am in the process of setting up a page that allows users to upload a txt file (specifically a log file generated by another program) and then modify the text as needed. Initially, my goal is to simply console.log the text, but eventually, I pl ...

Dealing with issues of toggling visibility with jQuery when using a dropdown menu

Inside a hidden drop down div, the focus is on "DC" right now. In the image below, we are looking at sales: HTML: <td class="edit"> <select class="touch" style="display: none;"> <option value="11">Rebuying</option><option value ...

Modify the state of a separate component in React when an onClick event occurs

I am attempting to pass state through props and I am looking to reverse it when I click an element in another component. Is this achievable? Header Component: class Header extends Component { constructor(props) { super(props); this.state = { ...

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...