加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular 1.5 $onInit not firing – typescript

发布时间:2020-12-17 17:16:57 所属栏目:安全 来源:网络整理
导读:我正在尝试将Angular 1.5应用程序的部分转换为TypeScript.我没有收到任何错误,但$onInit()方法不再触发.我包括我的代码( JavaScript)和不工作的代码(TypeScript) Javascript版本(工作): angular .module('app') .component('appProductList',{ templateUrl:
我正在尝试将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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读