Angularjs 角度1.5$onInit未触发-类型脚本

Angularjs 角度1.5$onInit未触发-类型脚本,angularjs,typescript,components,Angularjs,Typescript,Components,我正在尝试将Angular 1.5应用程序的部分转换为TypeScript。我没有收到任何错误,但是$onInit()方法不再触发。我包括了我的代码(JavaScript)和不工作的代码(TypeScript) Javascript版本(工作): 类型脚本版本($onInit从不激发): angular .module('应用程序') .component('appProductList'{ templateUrl:“/src/product list/product list.componen

我正在尝试将Angular 1.5应用程序的部分转换为TypeScript。我没有收到任何错误,但是$onInit()方法不再触发。我包括了我的代码(JavaScript)和不工作的代码(TypeScript)

Javascript版本(工作):

类型脚本版本($onInit从不激发):

angular
.module('应用程序')
.component('appProductList'{
templateUrl:“/src/product list/product list.component.html”,
控制器:ProductListController
});
类ProductListController{
产品:阵列;;
构造函数(私有$location:ng.ILocationService,
私有产品服务:产品服务){}
$onInit(){
this.products=新数组();
this.ProductService.getProducts()
.然后((res:ng.ihttpromisecallbackarg)=>{
本产品=资源数据;
},error=>console.log(error));
} 
选择产品(产品){
此.location.path('/product/'+product.id);
}
} 

答案,类不会被提升,因此必须在引用它们之前声明它们

从MDN文档:

吊装: 函数声明和类声明之间的一个重要区别是函数声明被挂起而类声明不被挂起。您首先需要声明类,然后访问它,否则类似以下的代码将抛出引用错误:


我对typescript中的内容不太确定,但我知道一般情况下类不会起作用,所以在引用它们之前需要声明它们。换句话说,尝试将类移动到其他代码之上。也许只需在构造函数中抛出一个控制台日志,以确保该类正常工作。谢谢@shing,将该类移到我声明的上方即可。。所以函数提升而类不提升?正确,函数语句(带名称的函数)将提升,因此您几乎可以在您的范围内的任何位置声明它们,并且可以访问它们。查看mdn文档中的类:“函数声明和类声明之间的一个重要区别是函数声明被提升而类声明不被提升。您首先需要声明类,然后再访问它,否则类似以下的代码将抛出引用错误:”
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);
    }
}
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);
    }
}