Angularjs和Typescript:错误:[$injector:unpr]未知提供程序
我有一个非常简单的网页:Angularjs和Typescript:错误:[$injector:unpr]未知提供程序,angularjs,dependency-injection,typescript,Angularjs,Dependency Injection,Typescript,我有一个非常简单的网页: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <title></title> </head> <body ng-app="nawApp">
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title></title>
</head>
<body ng-app="nawApp">
<div ng-controller="StudentUse">
{{fullname}}
</div>
<script src="../Scripts/angular.js"></script>
<script src="../Scripts/angular-route.js"></script>
<script src="../Scripts/app.js"></script>
<script src="StudentUse.js"></script>
<script src="ServiceHttp.js"></script>
</body>
</html>
首先,我想建议在顶部添加angular.d.t
/// <reference path="../scripts/typescript/angular.d.ts" />
/// <reference path="../scripts/app.ts" />
/// <reference path="ServiceHttp.ts" />
/// <reference path="Student.ts" />
在代码中的某个地方,例如在控制器中,您应该通过
在控制器功能中
控制器构造函数
private ServiceHttp:any;
constructor(ServiceHttp .... // other dependencies){
this.ServiceHttp = ServiceHttp;
}
在ctrl函数中
someCtrlFunction(){
this.ServiceHttp.exampleFunction().then(function(resp){
// success resolved with your response
})
}
谢谢,但是为什么我需要$q:ng.IQService和$log:ng.ILogService。这只是一个例子,告诉你如何注入依赖项:)如果你不需要,你可以删除它们:)谢谢。嗯,我根据你的建议调整了代码-它有效:-)。正如我所说的,我想将该服务用于HTTP-REST请求,所以我只需要$HTTP。您的测试目的我刚刚返回了“Hello World”的内容,但是现在我添加了其余的内容,所以这个.http.get(URL).success…,但是似乎http没有以正确的方式初始化。我用“serviceHttp.exampleFunction();”调用exampleFunction()。这不是正确的方法…:-)你能帮我做这个吗。。。对不起,这似乎是个愚蠢的问题。。。我知道您的意思是希望在exampleFunction http调用并返回承诺,然后在代码中执行类似于serviceHttp.exampleFunction()的操作。然后(function(){alert('succes')})我建议将此模式用于服务:
/// <reference path="../scripts/typescript/angular.d.ts" />
/// <reference path="../scripts/app.ts" />
/// <reference path="ServiceHttp.ts" />
/// <reference path="Student.ts" />
module nawApp {
export class ServiceHttp {
private http: ng.IHttpService;
private q: ng.IQService;
private log: ng.ILogService;
constructor($http: ng.IHttpService,$q: ng.IQService,$log: ng.ILogService) {
this.http = $http;
this.q = $q;
this.log = $log;
}
exampleFunction(){
var defer = this.q.defer();
this.http.get('http://example.com').then(
(response: ng.IHttpPromiseCallbackArg<any>) => {
defer.resolve(response);
}
},
(err: ng.IHttpPromiseCallbackArg<any>) => {
defer.reject(err.data);
}
)
return defer.promise;
}
static Factory($http:ng.IHttpService, $q:ng.IQService,$log: ng.ILogService) {
return new ServiceHttp($http, $q, $log);
}
}
}
nawApp.app.factory('ServiceHttp', nawApp.ServiceHttp.Factory);
private ServiceHttp:any;
constructor(ServiceHttp .... // other dependencies){
this.ServiceHttp = ServiceHttp;
}
someCtrlFunction(){
this.ServiceHttp.exampleFunction().then(function(resp){
// success resolved with your response
})
}