Plain Javascript as Angular 2 service
Update 1: Based on the comments, the previous solution will be not help you.
You can do that by using OpaqueToken in Angular2
1. Create a Token that is used to find an instance as below in a separate ts file.
import { OpaqueToken } from '@angular/core'
export let name_of_The_Token = new OpaqueToken('name_Of_The_Window_Object');
2. In your App.module, you need to import and declare a variable that is the name of your window object which makes the Token as a angular2 service so that you can use properties, methods in that javascript file across your components.
import { name_of_The_Token } from '/* file_Path */';
declare let name_Of_The_Window_Object : any; //below your import statements
Step 3: Inject it to providers array of your module.
{ provide : name_of_The_Token , useValue : name_Of_The_Window_Object }
Guidance to use this token in components
-
Import the token just like any other service and @Inject from angular-core
import { name_of_The_Token } from '/* file_Path */'; import { Inject } from '@angular/core';
-
In constructor of the component
constructor(@Inject( name_of_The_Token ) private _serviceObject : any )
-
Any where in your component you can use the variables and methods of your javascript file as
this._serviceObject.method1() this._serviceObject.variable1 .....
Note: One drawback is that you will not get intellisense.
Overcoming it: If you are looking for intellisense you need to wrap the methods and variables inside an interface and use it in the type**(instead of any)** of your token as
export interface myCustom {
method1(args): return_Type;
method2(args): void;
.....
}
LIVE DEMO of ToasterService