简体   繁体   中英

Angular 1.5 $onInit not firing - typescript

I'm attempting to convert parts of an Angular 1.5 application to TypeScript. I'm not getting any errors but the $onInit() method is no longer firing. I'm including my code that works (JavaScript) and the not working code (TypeScript)

Javascript version (working):

angular
    .module('app')
    .component('appProductList', {
        templateUrl: '/src/product-list/product-list.component.html',
        controller: ProductListController
    });

function ProductListController($location, ProductService) {
    var ctrl = this;

    ctrl.$onInit = init;
    ctrl.selectProduct = selectProduct;

    function init(){
        ctrl.products = [];

        ProductService.getProducts()
            .then(res => {
                ctrl.products = res.data;
            }, error => console.log(error));
    }

    function selectProduct(product){
        $location.path('/product/' + product.id);
    }
}

TypeScript version ($onInit never fires):

angular
    .module('app')
    .component('appProductList', {
        templateUrl: '/src/product-list/product-list.component.html',
        controller: ProductListController
    });

class ProductListController{
    products: Array<Product>;

    constructor(private $location: ng.ILocationService, 
                private ProductService: ProductService) {}

    $onInit() {
        this.products = new Array<Product>();

        this.ProductService.getProducts()
            .then((res: ng.IHttpPromiseCallbackArg<Array<Product>>) => {
                this.products = res.data;
            }, error => console.log(error));
    } 

    selectProduct(product){
        this.$location.path('/product/' + product.id);
    }
} 

Answer, classes do not hoist, therefor they must be declared before they are referenced.

From the MDN docs:

Hoisting: An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError:

MDN: Classes

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