Reputation: 165
I am making a web application in angular 2 and for some reasons I am unable to pass my data from one component to another or one service to another, I am using services to use this but there is some issue.I want to pass the selected item from the gameBuy and add it to cart when Add to cart button is pressed from the gameBuy component. but I am unable to do so please help.
service code of 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);
}
}
service code of cart:
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 file:
@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 file:
@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 file:
<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>
Upvotes: 1
Views: 4590
Reputation: 73357
The issue you are facing is that you are providin service in providers
array in components, this means, that you will have a separate instance of the services in each component. You need to apply the service at the module level so that the service is truly a shared service, i.e components in that module share the same instance of the service.
So remove providers array completely from the component(s):
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
// providers:[cartService] REMOVE!!
})
and instead set it in your ngModule:
@NgModule({
declarations: [...],
imports: [...],
providers: [
cartService // here!
]
)}
PS, just a styling suggestion, usually we use camel case, i.e CartService
in this case.
Upvotes: 1
Reputation: 482
add following code:
// 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();
}
}
Try with BehaviourObject instead of EventEmitter.
Hope it will help you :)
Upvotes: 0