【问题标题】:Angular 1.5 $onInit not firing - typescriptAngular 1.5 $onInit 未触发 - 打字稿
【发布时间】:2016-12-13 13:56:00
【问题描述】:

我正在尝试将 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', {
        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);
    }
} 

【问题讨论】:

  • 我不确定在打字稿中,但我知道一般类不会提升,因此您需要在引用它们之前声明它们。换句话说,尝试将类移到其他代码之上。也许只是在构造函数中抛出一个控制台日志以确保类正常工作。
  • 谢谢@hsiung,将类移到我的角度声明上方是有效的。所以函数提升和类没有?
  • 正确,函数语句(带有名称的函数)会提升,因此您几乎可以在范围内的任何位置声明它们并且它们将是可访问的。查看 mdn 文档中的类:“提升函数声明和类声明之间的一个重要区别是函数声明被提升而类声明不是。你首先需要声明你的类然后访问它,否则代码如下将抛出一个 ReferenceError:"

标签: angularjs typescript components


【解决方案1】:

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

来自 MDN 文档:

吊装: 函数声明和类声明之间的一个重要区别是函数声明是提升的,而类声明不是。你首先需要声明你的类然后访问它,否则像下面这样的代码会抛出一个ReferenceError:

MDN: Classes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2016-10-27
    • 2017-05-03
    • 1970-01-01
    • 2016-11-21
    • 2019-12-31
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多