Использование Pusher в Angular 6+ - PullRequest
0 голосов
/ 03 ноября 2018

Я следовал следующему уроку по использованию толкателя с углом: https://pusher.com/tutorials/angular-realtime

Однако я думаю, что при использовании Angular 6 или выше, возможно, придется изменить несколько вещей.

Я не могу установить связь между экземплярами моего приложения на моем клиенте во время тестирования. Может кто-нибудь указать мне, где я мог ошибаться?

Я не получаю никаких ошибок ни в своей консоли, ни в окне моего серверного терминала, но обновления отражаются только на текущем активном окне. Он должен обновляться во всех браузерах с запущенным приложением. Заранее спасибо. Был бы признателен за понимание этого. До этого не работал с веб-сокетами:)

В angular.json:

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

В средах> environment.ts:

export const environment = {
production: false,
pusher: {
key: KEY FROM PUSH DASHBOARD,
cluster: CLUSTER FROM PUSHER DASHBOARD
 }
};

толкатель-service.service:

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';
// We declare our Pusher constant so that Angular knows that we are using the Pusher class from an external script
declare const Pusher: any;


@Injectable()
export class PusherService {
  pusher: any;
  channel: any;

  constructor( private http: HttpClient  ) {
    this.pusher = new Pusher(environment.pusher.key, {
      cluster: environment.pusher.cluster,
      encrypted: true
    });
    // Subscribe to the events-channel
    this.channel = this.pusher.subscribe('events-channel');
  }

  // Make a post to our backend with the number of likes
  like( num_likes ) {
    this.http.post('http://localhost:3120', {'likes': num_likes})
    .subscribe(data => {});
  }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PusherService } from './services/pusher-service.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    PusherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { PusherService } from './services/pusher-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'Like App Example using sockets using Pusher';
  likes: any = 0;

  // Pusher service injected here
  constructor( private pusherService: PusherService) {}

  ngOnInit() {
    this.pusherService.channel.bind('new-like', data => {
      this.likes = data.like;
    });
  }

  /**
   * Add to the number of likes to the server
   */
  like() {
    this.likes = parseInt(this.likes, 10) + 1;
    this.pusherService.like( this.likes );
  }
}

файл app.component.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Websocket Chat Example</title>
</head>

<body>

  <div class="container main-app text-center">
    <div class="row">
      <div class="col">
        <h1> {{ title }} </h1>
      </div>
    </div>

    <div class="row">
      <div class="col">
        <img src="../assets/images/angry-nerds.png" alt="Angry Nerds">
      </div>
    </div>

    <div class="row">
      <div class="col">
        <p> {{ likes }} likes</p>
        <button class="btn btn-lg btn-success" (click)="like()">Like Image</button>
      </div>
    </div>
  </div>

</body>
</html>

В новом каталоге: сервер> .env:

PUSHER_APP_ID='KEY'
PUSHER_API_KEY='KEY'
PUSHER_API_SECRET='KEY'
PUSHER_API_CLUSTER='KEY'

server> server.js:

/**
 * Import Node Modules
 */

 require("dotenv").config();
 const cors = require("cors");
 const Pusher = require("pusher");
 const express = require("express");
 const bodyParser = require("body-parser");

 /**
  * create express app
  */
 const app = express();

/**
  * Load middlewares
*/

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

/**
 * create Pusher client
 */
const pusher = new Pusher({
  appId: `${process.env.PUSHER_APP_ID}`,
  key: `${process.env.PUSHER_API_KEY}`,
  secret: `${process.env.PUSHER_API_SECRET}`,
  cluster: `${process.env.PUSHER_APP_CLUSTER}`,
  encrypted: true
});

/**
 * Create our routes
 */
app.post( "/", function(req, res) {
  /**
   * Trigger push event
   */
  console.log('Received Like!');
  pusher.trigger("events-channel", "new-like", {
    likes: `${req.body.likes}`
  });
});

// Assign application
var httpServer = app.listen(3120, 'localhost', function() {
  httpServer.address().port;
  console.log("webSocket Server listening on localhost:3120");
});
...