I'm loading socket.io in my application like so:
index.html
<script src="http://myapp.com/socket.io/socket.io.js"></script>
...
// Angular stuff
I have a component called Socket
which requires window.io
to work.
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';
@Injectable()
export class Socket {
public isConnected: boolean = false;
constructor(public events: Events) {
if (typeof window.io === "undefined") {
throw new Error("Socket.io is undefined.");
}
this.io = window.io;
}
connect() {
this.io.connect("...");
}
listen() {
}
}
In theory, it may work (didn't test) but it is not a good practice to inject stuff from window scope into classes.
Is there any way to do it like this:
import { SocketIODriver } from 'socket.io';
import { Socket } from 'App/Socket/Socket';
@Component({
templateUrl: 'layout.html'
})
export class ConferenceApp {
constructor(
public io: io,
public Socket: Socket
) {
this.socket = new Socket(new SocketIODriver());
}
}
Thank you.
Ps. IIRC, socket.io has to be loaded from the server, that's why I load it from my server. If it can be placed into my JS folder, that would be even better.
While this seems to be still working with Angular 8, be cautious, it's an old answer
Angular > 1 works with injectors. Each injector is scoped to a specific module and provides the data you'd like your module to receive.
For example, you can define an object of the shape: { useValue: 'theValueToInject' }
and make it available at any level of your tree.
If you want to provide such an object to your module, you will have to rely on the providers
property of the @NgModule
decorator. Then you can construct your own object using
{provide: 'NameToInvoke', useValue: alreadyInitializedValue}
Since window
is already an instanciated object, you can rely on this approach to provide it to your module:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
{ provide: 'Window', useValue: window }
],
bootstrap: [AppComponent]
})
export class AppModule { }
And so, you can use it like :
constructor(@Inject('Window') private window: any) {} // or window type, I don't know what it's exactly