[英]Cannot write JavaScript in the body of a class
在C#中,建议避免在构造函数中加载数据。 而是实例化一个类,然后在需要执行诸如从数据库加载数据之类的操作时创建一个方法。 在具有TypeScript的AngularJS中,是否是通过构造函数在控制器中加载时运行方法的唯一方法? 即,以下代码无法在TypeScript中编译。 那是因为我必须从构造函数中调用Activate吗?
class BaHomeController{
entries: any[];
static $inject = ["$http"];
constructor(
private $http
){}
private loadEntries() {
this.$http.get("api/blogEntries").then(function(response) {
this.entries = response.data;
});
}
private activate(): void{
this.loadEntries();
}
activate();
}
您的格式对我来说一团糟,也许这种格式会让事情变得更清楚。 同样,您不能像在类声明中那样调用Activate,这就是为什么您不进行编译的原因。
class BaHomeController{
// private field
entries: any[];
static $inject = ["$http"];
constructor(private $http)
{
//This is calling the private activate method in the constructor
this.activate();
}
//private method
private loadEntries()
{
this.$http.get("api/blogEntries").then(function(response) {
this.entries = response.data;
});
}
//private method that return void
private activate(): void
{
this.loadEntries();
}
}
您还可以解析路线中的数据:
angular.module('app.something')
.config(routing);
routing.$inject = ['$stateProvider'];
function routing(stateProvider: angular.ui.IStateProvider) {
stateProvider
.state('home', {
url: '/home',
templateUrl: 'scripts/home/home.html',
controller: 'app.something.BaHomeController',
controllerAs: 'vm',
resolve: {
entries: loadEntries
}
})
}
function loadEntries() {
//Make call to entries service
return entriesService.getEntries(); //Make the http call in the service and also deal with the promise there.
}
您的控制器
class BaHomeController{
static $inject = ["$http"];
constructor(private $http: ng.IHttpService,
public entries: any){ }
}
另一种方法是在控制器中具有一个init函数,并从html调用它,以便在页面加载时被调用
class LayoutController {
dataModel: app.layout.TopSearchHtmlDataModel;
vehicleSearchModel: app.layout.VehicleSearchModel;
static $inject = [
'app.services.SlideService',
'app.services.VehicleService',
'app.services.CommonUtils',
'$rootScope',
'$filter',
'$state'
];
constructor(
private slideService: app.services.SlideService,
private vehicleService: app.services.VehicleService,
private commonUtils: app.services.CommonUtils,
private $rootScope: ng.IRootScopeService,
private $filter: any,
public $state: ng.ui.IStateService) {
this.dataModel = new app.layout.TopSearchHtmlDataModel();
this.vehicleSearchModel = new app.layout.VehicleSearchModel();
}
init(): void {
this.getAllMakeAndModelData();
this.getIrishCounties();
this.getMinYearArray();
this.getLogoSlides();
}
//Private methods omitted
}
html:
<div ng-init="vm.init()"></div> //assuming you use controllerAs vm
无论如何,对数据的调用都是异步的,因此将调用放在构造函数中似乎没什么大不了的。
你有尝试过吗?
constructor(){
this.loadEntries();
}
请注意, loadEntries
内部回调的异步特性意味着您的控制器将以this.entries
存在,直到$http.get
调用成功返回为止
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.