【发布时间】:2016-08-06 00:50:35
【问题描述】:
我有以下 Javascript 文件,我想将其导入到我的 Angular 2 项目中,而无需在 Typescript 中重写整个内容。
当一切都正确绑定时,我收到以下错误...
“异常:类型错误:无法读取未定义的属性‘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”对象,它就会中断。
-
我的直觉是问题出在 .d.ts 文件中,但不确定解决方案。
-
.d.ts文件应该不会影响您的应用程序的实际运行方式。其中没有操作代码。 -
所以你的解决方案是?
标签: javascript typescript angular