我想从节点脚本中重用Angular2的@angular/http
模块。我正在使用节点v4.6.0,@angular/http
版本2.1.2从npm
获取它。
在这个特定的情况下,我想这样做,这样我就可以轻松地隔离模块,确认它的行为,并玩弄它(我的意思是我应该能够正确 - 这就是为什么它被称为模块......)。但我也在重复使用在节点中没有固有浏览器依赖性的Angular模块的一般建议。
关闭我正在查看的Web应用程序如何使用我尝试过的模块:
myUrl = '...'
http = require('@angular/http')
Http = new http.Http()
Http.get(myUrl).then(result => console.log(result))
得到了:
TypeError:无法读取undefined的属性'merge' 在mergeOptions(/home/sam/node_modules/@angular/http/bundles/http.umd.js:1578:30) 在Http.get(/home/sam/node_modules/@angular/http/bundles/http.umd.js:1672:45) 在repl:1:6 在REPLServer.defaultEval(repl.js:262:27) 在界(domain.js:287:14) 在REPLServer.runBound [as eval](domain.js:300:12) 在REPLServer。 (repl.js:431:12) 在emitOne(events.js:82:20) 在REPLServer.emit(events.js:169:7) 在REPLServer.Interface._onLine(readline.js:212:10)
那么,它完成了吗?可以吗?如何在Http的特定情况下进行处理?
答案 0 :(得分:1)
经过一些(很多)关于NG2(Angular2)的学习之后,我意识到一旦你学会了它就会显而易见:NgModules不仅仅是像“模块”这个术语所暗示的那样的简单容器。他们负有非常具体的责任,并与NG2核心紧密结合。所以你不能只是将它们导入节点。你需要一个bootstrapped NG2核心模块来处理NG2中的任何事情。由于注射系统,访问由Http
提供的注射服务HttpModule
再次变得更加复杂。
使用NG2的业力测试框架和实用程序,我能够对NG2的Http
服务进行一定程度的隔离访问。整个测试设置非常复杂,但是它们都在QuickStart应用程序中完成(测试设置本质上为您提供了一个自举NgModule,在服务器环境中可以运行测试)。我删除了快速启动应用程序并添加了一个简单的单元测试,然后运行npm test
:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { HttpModule, Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
describe('Test frame for accessing Http!', function () {
let http: Http
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpModule ]
})
.compileComponents();
}));
beforeEach(() => {
http = TestBed.get(Http);
});
it('Test some HTTP', () => {
http.get('/base/foo.json').toPromise()
.then((r: Response) => console.warn(r))
.catch((e: any) => console.warn('An error occured'))
});
});
支持这个的服务器是业力,所以你可能需要调整它的配置,告诉它提供任何地方的服务......