我有以下Javascript文件,我想導入到我的Angular 2項目中,而無需在Typescript中重新編寫整個內容。Angular 2 - TypeError:無法讀取未定義的屬性'createMessage'
當一切都正確綁起來,我得到以下錯誤...
「EXCEPTION:類型錯誤:未定義無法讀取屬性‘的CreateMessage’」
這裏是我的相應文件...
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;
}
}
奇怪我可以得到這個工作時applicationAPI.js看起來像下面的相同applicationAPI.d.ts文件。
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;
}());}());
上需要添加別的什麼,這種情況下的工作有什麼想法?這不是明擺着給我...
這是呼叫來自哪裏...
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();
}
}
你在哪一行得到錯誤?它看起來並不像你實際上在任何地方調用'SystemFactory.createMessage()' –
這個調用來自我的「home.component.ts」文件,我添加了它。對於後面的用例,一切正常,但是一旦我在它打破的js中引入了「myApplication」對象。 – Daz
我的直覺是問題出在.d.ts文件中,但我不確定解決方案。 – Daz