javascript - Angular : Transfer a single list item from array list using service to another service?

标签 javascript arrays angular typescript angular-services

将单个项目从列表项转移到购物车列表。

我正在开发一个Angular网络应用程序,希望当我单击按钮时,数组的单个项目从一个服务转移到另一个服务,并且也被转移在另一个组件上。我已经通过整个数组的传输成功实现了它,但我遇到了单个项目的问题。请帮忙。

<小时/>

我想要的是,当我单击添加到购物车按钮时,单击的列表项只会被传输,而不是列表项数组。

<小时/>

buyGame.html 文件

<div class="col-xs-6">
    <a class="list-group-item clearfix" style="background-color:rgb(3, 0, 48)" *ngFor="let buying of buy">
        <div class="pull-left" style="max-width:330px">
            <h5 style="color:white">{{buying.names}}</h5>
            <p style="color:white">{{buying.desc}}</p>
            <button class="btn btn-danger ; pull-left" (click)= "onAddToCart()">Add To Cart</button>
        </div>
        <div>
            <span class="pull-right">
                <img [src]="buying.getImg" alt="image not loaded" class="img-responsive" style="max-height:100px">
            </span>
        </div>
    </a>
</div>

buygame.service.ts 文件:

import { gameBuy } from "./buygame.model";
import { Injectable,EventEmitter } from "@angular/core";
import { cartService } from "./cart.service";

@Injectable()
export class gameService{

    private gameServ: gameBuy[] = [
        new gameBuy('batman','Batmobile and enhancements to signature features',"https://www.geek.com/wp-content/uploads/2016/02/batmans-625x352.jpg"),
        new gameBuy('GTA 5',
        "PlayStation 3 or Xbox 360 will be able to transfer their current Grand Theft Auto Online characters and progression to their choice of PlayStation 4 Xbox One or PC",
        "http://onlysp.com/wp-content/uploads/2015/01/maxresdefault.jpg")
    ];

    constructor(private cartSer: cartService){}

    getBuyingList(){
        return this.gameServ.slice();
    }

    addItemToCart(game:gameBuy[]){
        this.cartSer.addItem(game);
    }
}

buyGame.component.ts:

import { Component, OnInit,Input } from '@angular/core';
import { gameBuy } from '../shared/buygame.model';
import { gameService } from '../shared/buygame.service';

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

  @Input() buy:gameBuy[];

  constructor(private service: gameService) { }

  ngOnInit() {
    this.buy = this.service.getBuyingList();
  }

  onAddToCart(){
 this.service.addItemToCart(this.buy);
  }
}

cart.component.ts:

import { Component, OnInit} from '@angular/core';
import { cartModel } from '../shared/cart.model';
import { cartService } from '../shared/cart.service';
import { gameBuy } from '../shared/buygame.model';

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

   cart:gameBuy[];

  constructor(private service: cartService) { }

  ngOnInit() {
    this.cart = this.service.getCartItem();
  }

}

cart.service.ts:

import { cartModel } from "./cart.model";
import { EventEmitter } from "@angular/core";
import { gameBuy } from "./buygame.model";

export class cartService{

    cartChanged = new EventEmitter<gameBuy[]>();
    private cart: gameBuy[] = [
        new gameBuy('Batman','Batman is a cool game','https://images-na.ssl-images-amazon.com/images/I/91lu5KHSm3L._SY445_.jpg'),
        new gameBuy('Gta 5','online game of GTA','https://www.rockstargames.com/V/img/global/order/mobile-cover.jpg')
    ];

    getCartItem(){
        return this.cart.slice();
    }

    addItem(cart:gameBuy[]){
        this.cart.push(...cart);
        this.cartChanged.emit(this.cart.slice());
    }
}

cart.model.ts:

export class cartModel{
    constructor(public cartName: string,public cartDesc: string,public cartImage:string){}
}

buygame.model.ts:

export class gameBuy{
    constructor(public names:string, public desc:string, public getImg:string){}
}

最佳答案

您需要在模板中指定要添加到购物车的确切商品:

(click)= "onAddToCart(buying)"

然后将其作为 onAddToCart 方法参数直接传递给您的服务:

onAddToCart(buying: gameBuy){
  this.service.addItemToCart(buying);
}

此外,您的 buygame 服务方法应该接受单个项目,而不是列表:

addItemToCart(game: gameBuy){
    this.cartSer.addItem(game);
}

最后,cart 服务也应该更新(只是为了推送单个项目)

 addItem(cart:gameBuy){
    this.cart.push(cart);
    this.cartChanged.emit([...this.cart]); // slice() is ok too if you need a copy
}

关于javascript - Angular : Transfer a single list item from array list using service to another service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48357884/

相关文章:

javascript - Vue JS 在 console.log 上返回 [Object object] 并在 JSON.parse 上返回未定义

c++ - 可视化多维数组如何放置在内存中的方法?

c - 修改字符串(字符数组)

angular - 如何在 Angular Material Table 单元格中显示一张或多张图像

Angular 日期管道在文本框中无法正常工作

javascript - Bootstrap 4 Button Group wrapping fix border-radius

javascript - 页面加载时初始化 "hidden"工具提示

javascript - d3 v4 模块从 require 切换到 import

php - 如何合并多个未知长度的平面数组,转置它们,然后形成一维数组?

javascript - Angular 中的随机动画