我正在 angular 2 中制作网络应用,由于某些原因,我无法将我的数据从一个组件传递到另一个组件或一个服务到另一个,我使用服务来使用它但有一些问题。我想从 gameBuy 传递所选项目并将其添加到购物车当从gameBuy组件中按下添加到购物车按钮时。但我无法帮助你。
buyGame的服务代码:
import { gameBuy } from "./buygame.model";
import { Injectable } 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",
"https://vignette.wikia.nocookie.net/gtawiki/images/7/76/CoverArt-GTAV.png/revision/latest?cb=20130826184215")
];
constructor(private cartService: cartService){}
getBuyingList(){
return this.gameServ.slice();
}
addItemToCart(game:gameBuy[]){
this.cartService.addItem(game);
}
}
购物车的服务代码:
import { cartModel } from "./cart.model";
import { EventEmitter } from "@angular/core";
export class cartService{
cartChanged = new EventEmitter<cartModel>();
cart: cartModel[] = [
new cartModel('Batman','Batman is a cool game','https://images-na.ssl-images-amazon.com/images/I/91lu5KHSm3L._SY445_.jpg'),
new cartModel('Gta 5','online game of GTA','https://www.rockstargames.com/V/img/global/order/mobile-cover.jpg')
];
getCartItem(){
return this.cart.slice();
}
addItem(carting:cartModel[]){
this.cart.push(...carting);
this.cartChanged.emit(this.cart.slice());
}
}
cart.ts文件:
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
providers:[cartService]
})
export class CartComponent implements OnInit {
cart:cartModel[];
constructor(private service: cartService) { }
ngOnInit() {
this.cart = this.service.getCartItem();
}
}
buyGame.ts文件:
@Component({
selector: 'app-buy-game',
templateUrl: './buy-game.component.html',
styleUrls: ['./buy-game.component.css'],
providers: [gameService]
})
export class BuyGameComponent implements OnInit {
@Input() buy:gameBuy[];
constructor(private service: gameService) { }
ngOnInit() {
this.buy = this.service.getBuyingList();
}
onAddToCart(){
this.service.addItemToCart(this.buy);
}
}
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:350px">
<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>
答案 0 :(得分:1)
您面临的问题是您在组件中的providers
数组中提供服务,这意味着您将在每个组件中拥有单独的服务实例。您需要在模块级别应用服务,以便该服务真正是共享服务,即该模块中的组件共享相同的服务实例。
因此,从组件中完全删除提供者数组:
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
// providers:[cartService] REMOVE!!
})
而是在你的ngModule中设置它:
@NgModule({
declarations: [...],
imports: [...],
providers: [
cartService // here!
]
)}
PS,只是一个样式建议,通常我们使用驼峰案例,即CartService
。
答案 1 :(得分:0)
添加以下代码:
// Service code of cart
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
...
export class cartService{
private buyGameSub: BehaviorSubject<any>;
private buyGameEvent: any;
...
constructor(){
this.buyGameSub = new BehaviorSubject<any>({});
this.buyGameEvent = this.buyGameSub.asObservable();
}
subscribeBuyGameEvent(next, err?, complete?){
return this.buyGameEvent.subscribe(next, err, complete);
}
addItem(carting:cartModel[]){
this.cart.push(...carting);
this.buyGameSub.next(carting);
}
}
// Cart.ts file
import { Subscription } from 'rxjs/Subscription';
export class CartComponent implements OnInit {
gameBuySubscription: Subscription;
constructor(private service: cartService) {
this.subscribeGameBuy();
}
subscribeGameBuy(){
this.gameBuySubscription =
this.service.subscribeBuyGameEvent( carting => {
//use carting over here
});
}
}
ngOnDestroy(){
this.gameBuySubscription.unsubscribe();
}
}
尝试使用BehaviourObject而不是EventEmitter。
希望它会对你有所帮助:)。