我正在尝试在服务中包装http,以便所有数据库访问都通过我的频道
问题是,服务不能将注射剂传递给它们的构造函数(对吗?)所以我必须自己构建它。我正在使用代码:
<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">
var f, a, b, c, d, j, k, sum;
//f = String(window.prompt("Formel"));
a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));
sum = 0;
for (j = a; j <= b; j++) {
for (k = c ; k <= d ; k++) {
sum += j * j * k;
}
}
document.write(sum);
</script>
<noscript>
<p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>
但在尝试使用时:
import {Http,HTTP_BINDINGS,XHRBackend,BaseRequestOptions} from 'http/http';
import {Injector,bind} from 'angular2/di'
...
var injector = Injector.resolveAndCreate([
BaseRequestOptions,
XHRBackend,
bind(Http).toFactory(
function(backend, defaultOptions) {
return new Http(backend, defaultOptions);
},
[XHRBackend, BaseRequestOptions])
]);
this.http = injector.get(Http);
我收到错误:
实例化DBDriver时出错! (实体 - &gt; DBDriver)。 angular2.dev.js:22367原始异常:没有函数(){}的提供者! (function(_backend,_defaultOptions){ - &gt; function(_browserXHR,_baseResponseOptions){ - &gt; function(){})
答案 0 :(得分:2)
确保在您的服务中注入HTTP 请注意服务构造函数
中的 @Inject(http)@Inject(Http) public http: Http
请注意,http,至少在angular2 alpha45处,是在lib lib之外,因此你必须手动添加http lib
<script src="/node_modules/angular2/bundles/angular2.min.js"></script>
<script src="/node_modules/angular2/bundles/http.min.js"></script>
SERVICE
import {Http, Headers, HTTP_BINDINGS} from 'angular2/http';
import {Inject} from 'angular2/angular2'
constructor(@Inject(Http) public http: Http) {}
getQuote(): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get('http://localhost:3001/api/random-quote')
.map(res => res.text())
.subscribe(
data => resolve(data),
err => this.logError(err),
() => console.log("Random Quote Complete")
);
})
}
COMPONENT
import {Component, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
import {Http, Headers, HTTP_BINDINGS} from 'angular2/http';
import {ChuckService} from "./chuck-service";
@Component({
selector: 'hello-app',
template: `
{{quoteOfTheDay}}<br />
<button (click) = "getQuote()">Get new quote</button><br /><br />
`,
directives: [CORE_DIRECTIVES],
providers: [ChuckService, HTTP_BINDINGS]
})
export class HelloApp {
quoteOfTheDay: string = '';
constructor(public _chuckService: ChuckService) {
}
getQuote(){
this._chuckService.getQuote().then((resp) => this.quoteOfTheDay = resp);
}
}
bootstrap(HelloApp);
INDEX.HTML
<script src="/node_modules/es6-shim/es6-shim.min.js"></script>
<script src="/node_modules/systemjs/dist/system-csp-production.js"></script>