简体   繁体   English

Angular 1.5 $ onInit不触发-打字稿

[英]Angular 1.5 $onInit not firing - typescript

I'm attempting to convert parts of an Angular 1.5 application to TypeScript. 我正在尝试将Angular 1.5应用程序的一部分转换为TypeScript。 I'm not getting any errors but the $onInit() method is no longer firing. 我没有收到任何错误,但是$ onInit()方法不再触发。 I'm including my code that works (JavaScript) and the not working code (TypeScript) 我包括了有效的代码(JavaScript)和无效的代码(TypeScript)

Javascript version (working): JavaScript版本(有效):

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): TypeScript版本($ onInit永远不会触发):

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: 从MDN文档中:

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: 您首先需要声明您的类,然后访问它,否则类似以下的代码将引发ReferenceError:

MDN: Classes MDN:课程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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