gpt4 book ai didi

javascript - Angular2 - 在不同文件中拆分应用程序时出现引用错误

转载 作者:行者123 更新时间:2023-11-30 16:42:28 25 4
gpt4 key购买 nike

我正在尝试模块化 Angular 2 应用程序,将服务放在不同的文件中:

app.ts

/// <reference path="typings/angular2/angular2.d.ts" />
/// <reference path="./services.ts" />

import {Component, View, bootstrap, NgFor} from 'angular2/angular2';

@Component({
selector: 'my-app',
appInjector: [Service.TechnologiesService]
})
@View({
templateUrl: 'index-angular',
directives:[NgFor]
})

class MyAppComponent {
name: string;
technologies: Array<string>;

constructor(technologiesService: Service.TechnologiesService) {
this.name = 'DopAngular';
this.technologies = technologiesService.technologies;
}
}

bootstrap(MyAppComponent);

services.ts

module Service{
export class TechnologiesService {
technologies: Array<string>;
constructor() {
this.technologies = ['Angular 2 Developer Preview', 'Express', 'Jade', 'Gulp', 'Material Design Lite', 'Polymer', 'Sass', 'Karma', 'Mocha', 'Should', 'npm', 'Bower'];
}
}
}

这些文件编译成 js 没有错误,但是在浏览器中运行应用程序时我得到:

未捕获的 ReferenceError:服务未定义

关于如何解决这个问题有什么想法吗?

最佳答案

/// <reference path="./services.ts" />让编译器查看引用文件的类型信息,但不会导致生成/包含来自目标的任何代码。 (此功能主要为外部/环境库设计。)

要从您自己的代码中引用其他 TS 文件,您应该使用 import {...} from 'file';语法(参见 handbook ),例如

import {Service} from 'services'

您还需要在 TS 编译器配置和浏览器中配置模块加载器(SystemJS 或 requireJS)。

或者,您可以通过包含 services.ts 的编译版本来进行不可扩展的破解。在<script> app.ts 之前的标签并保持代码不变。

另请注意:您放入 services.ts 的内部模块是一个坏模式,关键字已弃用。请参阅上面链接的手册。

关于javascript - Angular2 - 在不同文件中拆分应用程序时出现引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31745853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com