我有一个购物车图标在我的标题组件,当用户付款,它从一条路线移动到另一条路线,购物车中的数值不会改变,除非我刷新页面。你知道如何实现它吗?
cartcomponent.ts
var user:User={name:formObj.value.name,email:formObj.value.email,phone:formObj.value.phone,address:formObj.value.address,payment:formObj.value.gender};
var currentcart=this.appservice.getproducts();
this.appservice.userinsert(user,currentcart).subscribe(
data => {this.emptydata=data;
console.log(this.emptydata.message);
},
error => { console.log(error); // Error if any
},
()=> {
//saving cart token to session storage for checking purpose
this.appservice.storecartoken(this.emptydata.message);
console.log(this.emptydata.message);
if(formObj.value.gender=="COD"){
this.spinner.hide();
this.appservice.removeall();
//removing cart so that we can start afresh
//this._flashMessagesService.show('Thanks For your Order ,Your transaction id is'+this.appservice.getcarttoken(), { cssClass: 'alert-success', timeout: 100000 });
//this.router.navigate(['/orderstatus']);
//this.appservice.removecarttoken();//removing cart token as well
//alert("Thanks For Your Cash On Delivery Order");
//location.href="/orderstatus";
this.router.navigateByUrl('/sample', {skipLocationChange: true})
.then(()=> this.router.navigate(["/orderstatus"]));
//moving to other page ,here the cart number is still visible
}
这是我的header.component.ts
import { Component, OnInit } from '@angular/core';
import { AppService } from '../app.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
cartremove=true;
//totalproducts:number;
constructor(private appservice:AppService) { }
//totalproducts= this.appservice.gettotalproducts();
//this function removes cart products and relaod the page
emptycart(){
this.appservice.removeall();
location.reload();
}
ngOnInit() {
if(this.cartremove){
this.appservice.removeall();
}
}
}
你知道如何实现这一点吗?这样当路线改变时,购物车组件就会被刷新,而不需要重新加载页面
发布于 2018-08-10 17:43:23
您需要使用Subject/Behavior Subject处理它。以下是代码
//服务中
private cartEvent = new Subject<any>();
public cartEvent$ = this.cartEvent.asObservable();
//在购物车组件中使用发出值
service.cartEvent.next(25);
//在头部组件中
您可以使用Subscribe访问它并更新组件
this.sub = service.cartEvent$.subscribe((value)=>{
this.cartCount = value;
});
https://stackoverflow.com/questions/51791508
复制相似问题