14

thanks in advance for helping me out. I'm trying to connect socket in one of my angular components, but in the console of the browser it throws an error saying that global is not defined at Object ../node_modules/socket.io-parser/is-buffer.js

This is my home.component.ts

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import * as io from 'socket.io-client';

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

  constructor() { }

  ngOnInit() {
  }

}


var socket = io();

If I take out the socket.io-client and socket = io(); the website is fine but when I include it, it crashes.

This is my package.json file

  "dependencies": {
    "@angular/animations": "^6.0.0",
    "@angular/common": "^6.0.0",
    "@angular/compiler": "^6.0.0",
    "@angular/core": "^6.0.0",
    "@angular/forms": "^6.0.0",
    "@angular/http": "^6.0.0",
    "@angular/platform-browser": "^6.0.0",
    "@angular/platform-browser-dynamic": "^6.0.0",
    "@angular/router": "^6.0.0",
    "@types/jquery": "^3.3.1",
    "@types/socket.io": "^1.4.33",
    "body-parser": "^1.18.3",
    "bootstrap": "^4.1.1",
    "core-js": "^2.5.4",
    "express": "^4.16.3",
    "jquery": "^3.3.1",
    "moment": "^2.22.1",
    "mongodb": "^3.1.0-beta4",
    "ng4-twitter-timeline": "^1.0.8",
    "popper.js": "^1.14.3",
    "rxjs": "^6.0.0",
    "socket.io": "^2.1.0",
    "socket.io-client": "^2.1.0",
    "zone.js": "^0.8.26"
  }

I first tried with just 'socket.io' which didn't work. I then started researching for a similar problem. I found nothing.

My end goal is to use socket to take data from forms and store in a database. Any help would be much appreciated.

UPDATE (POSSIBLE SOLUTION): 05/17/2018 You have to use:

(window as any) = window 

in polyfill.ts, this resolved the problem for me.

UPDATE (POSSIBLE SOLUTION #2): 05/29/2018

(window as any).global = window
Dre Jackson
  • 771
  • 10
  • 18
  • 1
    as you found the solution **that works fine by the way** please add it as answer – Ulrich Dohou Jul 26 '18 at 16:18
  • Possible duplicate of [Upgrading to angular-6.x gives "Uncaught ReferenceError: global is not defined"](https://stackoverflow.com/questions/50356408/upgrading-to-angular-6-x-gives-uncaught-referenceerror-global-is-not-defined) – Ulrich Dohou Jul 26 '18 at 16:24

3 Answers3

16
(window as any).global = window

As already mentioned in comment, add the above code in the polyfills.ts file.

Richang Sharma
  • 442
  • 3
  • 6
3

To fix this issue you need to open the file your_angular_setup/src/polyfills.ts and then add the line below at the bottom of the file.

    (window as any).global = window

and you will see that your issue is fixed.

Prashant Barve
  • 4,105
  • 2
  • 33
  • 42
2

In src/index.html in the head add

<script>
    var global = global || window;
</script>
bormat
  • 1,309
  • 12
  • 16