I want to import a JavaScript file into my Angular 2 project without having to rewrite it in Typescript. However, when everything is connected correctly, I encounter the following error...
"EXCEPTION: TypeError: Cannot read property 'createMessage' of undefined"
Here are the relevant files...
applicationAPI.js
var myApplication = myApplication || {};
(function(myApplication) {
myApplication.Message = function() {
this.m_messageContents = "New Message";
};
myApplication.Message.prototype.getApplicationMessageContents = function() {
return this.m_messageContents;
};
myApplication.SystemFactory = (function(){
var factory =
{
createMessage: function() {
return new myApplication.Message();
}
};
return factory;
}());
}(myApplication));
applicationAPI.d.ts
declare module "myApplicationAPI" {
export interface Message {
getApplicationMessageContents(): string;
}
export class SystemFactory {
static createMessage(): Message;
}
}
Interestingly, the code works with a slight change in applicationAPI.js while using the same applicationAPI.d.ts file.
applicationAPI.js
(function() {
this.Message = function() {
this.m_messageContents = "New Message";
};
this.Message.prototype.getApplicationMessageContents = function() {
return this.m_messageContents;
};
this.SystemFactory = (function(){
var factory =
{
createMessage: function() {
return new this.Message();
}
};
return factory;
}());}());
Any ideas on what else needs to be included for this specific scenario to work? It's not clear to me...
This is where the call originates from...
home.component.ts
import { Component, OnInit } from '@angular/core';
import * as myApp from "myApplicationAPI";
@Component({
moduleId: module.id,
selector: 'app-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css']
})
export class HomeComponent implements OnInit {
title: string;
constructor() {}
ngOnInit() {
this.title = myApp.SystemFactory.createMessage().getApplicationMessageContents();
}
}