Angular 2 from AngularJS



所以我有一个使用AngularJS的Web应用程序。我想将其更改为使用 Angular 2(使用 TypeScript 而不是 Javascript(。我正在努力获得以下部分,因为我不知道 Angular 等价物是什么。任何帮助将不胜感激。最主要的是我如何处理我的新数组 this.books 附带的$scope部分。

function CartController($scope) {
var store = null;
if(typeof(Storage) !== "undefined") {
var store = localStorage.getItem("lastName_cart");
}
if(store != null) {
$scope.books = JSON.parse(store);
} else {
$scope.books = 
[{ title: 'Absolute Java', qty: 1, price: 114.95},
{ title: 'Pro HTML5', qty: 1, price: 27.95},
{ title: 'Head First HTML5', qty: 1, price: 27.89}];
} 
$scope.total = 114.95 + 27.95 + 27.89;

$scope.removeBook = function(index) {
$scope.books.splice(index, 1);
$scope.updateTotal();
}
$scope.updateTotal = function() {
var sum = 0;
for (var i = 0; i < $scope.books.length; i++) {
sum += $scope.books[i].price * $scope.books[i].qty; 
}
$scope.total = sum;
}

Angular JS和Angular是完全不同的。 Angular 使用打字稿,它是基于组件的。没有控制器。

你的代码在 Angular 2 或 4 中应该是这样的

import { Component } from '@angular/core';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html'
})
export class CartComponent {
store = null;
book = [];
total: Number;
constructor() {
if(typeof(Storage) !== "undefined") {
this.store = localStorage.getItem("lastName_cart");
}
if(this.store != null) {
this.books = JSON.parse(store);
} else {
this.books = 
[{ title: 'Absolute Java', qty: 1, price: 114.95},
{ title: 'Pro HTML5', qty: 1, price: 27.95},
{ title: 'Head First HTML5', qty: 1, price: 27.89}];
} 
this.total = 114.95 + 27.95 + 27.89;
}
removeBook(index) {
this.books.splice(index, 1);
this.updateTotal();
}
updateTotal() {
let sum = 0;
for (let i = 0; i < this.books.length; i++) {
sum += this.books[i].price * this.books[i].qty; 
}
this.total = sum;
}
}

有用的助手如何将应用程序从 Angular 1.x 迁移到 Angular 2

最新更新