如何在标签/路由之间以角度共享数据?

时间:2019-05-20 06:55:55

标签: angular service

我有一个包含两个组件的Angular购物车应用程序。主页上将显示食品清单,用户可以单击食品清单,并将其添加到标题的购物车链接中。现在,用户应单击标题上的购物车链接,并使用角度路由将其重定向到购物车页面(/ home / cart)。现在,我想在此页面中显示添加到主页中的项目。

 
**Food Component TS**

import { Component, OnInit } from '@angular/core';
import { CartServiceService} from '../cart-service.service';

@Component({
  selector: 'app-food-details',
  templateUrl: './food-details.component.html',
  styleUrls: ['./food-details.component.css']
})
export class FoodDetailsComponent implements OnInit  {
  constructor( public cartService: CartServiceService) {}

  addToCart(data){
    this.cartService.sendCartData(data.innerHTML);
  }
}

**Cart Service**

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CartServiceService {
public newCartData = new Subject<any>();
constructor(){}

  sendCartData(data){
    this.newCartData.next(data);
  }
}

**Cart Component TS**

import { Component, OnInit } from '@angular/core';
import { CartServiceService} from '../cart-service.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {

  constructor( private CartService: CartServiceService) { }
  ngOnInit() {
   this.CartService.newCartData
   .subscribe(data => console.log(data));
  }
}
<a  style="float:right; width:100px" class="panel-footer btn btn-primary cart" href="/cart"><span class="glyphicon glyphicon-shopping-cart">
</span> Cart <span *ngIf="Cart.length>0">{{Cart.length}}</span></a>
<div style="margin-top:50px;"class="container">    
  <div class="row">
    <div class="col-sm-4">
      <div class="panel panel-primary">
        <div class="panel-heading" #item1>South Inidan Special Dosa</div>
        <div class="panel-body"><img src="../../assets/Dosa.jpg" class="img-responsive" style="width:100%" alt="Image"></div>
        <div class="panel-footer btn btn-primary cart" (click)="addToCart(item1)">Add to Cart</div>
      </div>
    </div>

0 个答案:

没有答案