I am trying to convert parts of an Angular 1.5 application to TypeScript. I am not getting any errors, but the $ onInit () method no longer works. I include code that works (JavaScript) and does not work (TypeScript)
Javascript version (work):
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 works):
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);
}
}
source
share