简体   繁体   中英

Cannot write JavaScript in the body of a class

In C#, it is recommended to avoid loading data in a constructor. Instead, instantiate a class, and then create a method when you need to do something like load data from the database. In AngularJS with TypeScript, is the only way to run methods on load in a controller through the constructor? Ie, the code below does not compile in TypeScript. Is that because I have to call activate from the constructor?

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();   
}

Your formatting is all messed up for me perhaps this format will make things more clear. Also you cannot call activate in your class declaration like you had it which is why you didn't compile.

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();
    }     
}

You could also resolve the data in the route:

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.
}

Your controller

class BaHomeController{

static $inject = ["$http"];    
constructor(private $http: ng.IHttpService,
            public entries: any){ }

}

An alternative is to have an init function in the controller and call it from the html so it gets invoked when the page loads

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

The call to the data will be asynchronous anyway, so putting the call in the constructor doesn't seem that big of a deal.

Have you tried this?

   constructor(){
        this.loadEntries();
   }

Be aware that the async nature of the callback inside of loadEntries means that your controller will exist with this.entries undefined until the $http.get call returns successfully

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM