angularjs – Angular 1.5 $onInit not firing – typescript

前端之家收集整理的这篇文章主要介绍了angularjs – Angular 1.5 $onInit not firing – typescript前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将Angular 1.5应用程序的部分转换为TypeScript.我没有收到任何错误,但$onInit()方法不再触发.我包括我的代码( JavaScript)和不工作的代码(TypeScript)

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

angular
    .module('app')
    .component('appProductList',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);
    }
}

解决方法

答案,课程不提升,因此必须在引用之前声明.

来自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:

MDN: Classes

猜你在找的Angularjs相关文章