更改路线时刷新标头组件

时间:2018-08-10 17:36:16

标签: javascript angular

我的标题组件上有一个购物车图标,当用户付款时,当它从一条路线移动到另一条路线时,除非刷新页面,否则cart中的数值不会改变。知道如何实现吗?

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();
   }
  }    
}

任何想法都可以实现,例如,当路线更改时,购物车组件将刷新而无需重新加载页面

1 个答案:

答案 0 :(得分:0)

您需要使用主题/行为主题来处理它。这是代码

//在使用中

private cartEvent = new Subject<any>();
public cartEvent$ = this.cartEvent.asObservable();

//使用购物车组件中的值发出

service.cartEvent.next(25);

//在标题组件中

您可以使用“订阅”访问它并更新组件

this.sub = service.cartEvent$.subscribe((value)=>{
   this.cartCount = value;
});