Angularjs Angular2服务未持久化数据
这是我的第一个Angular应用程序,它基于 我创建了一个Angularjs Angular2服务未持久化数据,angularjs,angular,Angularjs,Angular,这是我的第一个Angular应用程序,它基于 我创建了一个CartService来管理我的购物车,一个CartComponent来显示在我的导航栏中,还有一个CartReviewComponent来查看购物车 CartService位于app.module.ts的providers数组中我认为,这实际上创造了一个独生子女。 NavbarComponent与路由一起位于app.component.html文件中 将产品添加到购物车时,导航栏中的CartComponent会观察更改并更新以显示总美元
CartService
来管理我的购物车,一个CartComponent
来显示在我的导航栏中,还有一个CartReviewComponent
来查看购物车
CartService
位于app.module.ts
的providers数组中我认为,这实际上创造了一个独生子女。
NavbarComponent
与路由一起位于app.component.html
文件中
将产品添加到购物车时,导航栏中的CartComponent
会观察更改并更新以显示总美元
一旦我将路线发送到其他地方(另一个页面或购物车回顾),导航栏中的CartComponent
就会显示一个空购物车
如何使数据持久保存在购物车中,以便在我更改页面时购物车不是空的
谢谢
这是CartService
:
import {Injectable} from "@angular/core";
import {OrderedItem} from "../models/OrderedItem";
import {Subject} from "rxjs/Subject";
@Injectable()
export class CartService {
private orderedItems: OrderedItem[] = [];
//observable number sources
private cartPriceTotalSource = new Subject<number>();
private cartItemTotalSource = new Subject<number>();
//observable number streams
cartPriceTotal$ = this.cartPriceTotalSource.asObservable();
cartItemTotal$ = this.cartItemTotalSource.asObservable();
//message commands
addToCart(item: OrderedItem) {
this.orderedItems.push(item);
this.calculateCartTotals();
}
private calculateCartTotals()
{
let items = 0;
let price = 0;
this.orderedItems.forEach((element) => {
items += element.quantity;
price += element.quantity * element.item.price;
});
this.cartItemTotalSource.next(items);
this.cartPriceTotalSource.next(price);
}
}
上面发布的所有代码似乎都是正确的(或者现在已经足够正确了) 我的问题是,我正在使用
href=“定义的路线”
导航路线
正确的方法是访问[routerLink]
指令,如下所示:
[routerLink]=“定义的路由”]”
我意识到href
的方法是创建服务类的新实例,也许还有整个导航栏
如果有人能准确地解释发生了什么,我将不胜感激。您确定没有将
CartService
添加到提供商:[]
除了app.module.ts
之外的任何地方吗?不要将它添加到任何@组件({providers:[…])
。是的,除了app.module.ts
。你能给我们看看CartComponent吗?@Riv,我刚刚添加了it@MayNotBe,我也遇到了同样的问题,你有进一步的了解吗?
import {Component} from "@angular/core";
import {OrderedItem} from "../../models/OrderedItem";
import {CartService} from "../../services/cart.service";
@Component({
selector: "my-cart",
templateUrl: "app/components/cart/cart.component.html",
styleUrls: ["app/components/cart/cart.component.css"]
})
export class CartComponent {
itemTotal: number = 0;
priceTotal: number = 0;
constructor(
private cartService: CartService
) {
cartService.cartItemTotal$.subscribe(
itemTotal => this.itemTotal = itemTotal
);
cartService.cartPriceTotal$.subscribe(
priceTotal => this.priceTotal = priceTotal
);
}
}