简体   繁体   中英

Move object from one component to a sibling component in Angular5

I am working on a listing application that transfers an object from one component to an Identical sibling component. I'd also like to decrease the moves property by 1 with each move. I am having trouble with the actually pushing the selected item into the sibling array.

Here's a sample of my data...

import { player } from "./player";

export const PLAYERS: player[] = [
  {
    index: 1,
    photo: "../../assets/images/lonzo.jpeg",
    name: "Lonzo Ball",
    position: "G",
    moves: 5
  },
  {
    index: 2,
    photo: "../../assets/images/Brook.jpeg",
    name: "Brook Lopez",
    position: "C",
    moves: 5
  },

This is what I have in the services file...

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Subject } from 'rxjs/Subject';
import { player } from "./player";
import { PLAYERS } from "./players";
import 'rxjs/add/observable/of';
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { bench } from './bench';
import { RESERVES } from './RESERVES';

@Injectable()
export class DataService {

  public players = <any>PLAYERS;
  public bench = <any>RESERVES;


public getPlayers(): Observable<player[]> {
    return Observable.of(this.players);
  }

  public getReserves(): Observable<bench[]> {
    return Observable.of(this.bench);
  }

  addToReserves(data) {
    this.bench.next(data);
  }

  addToStarter(data) {
    this.players.next(data)
  }

    constructor() {}
}

This is what I have in the starters.ts file...

import { Component, OnInit } from "@angular/core";
import { DataService } from '../data.service'
import { player } from "../player";

@Component({
  selector: "app-roster-box",
  templateUrl: "./roster-box.component.html",
  styleUrls: ["./roster-box.component.css"],

})
export class RosterBoxComponent implements OnInit {
  moves: number = 5;
  btnText: string = "Move to Bench";
  players: Array<any>


constructor(public dataService: DataService) {}

getPlayers() : void {
    this.dataService.getPlayers()
      .subscribe(players => this.players = players);
  }


ngOnInit() {

      this.getPlayers();


  }
  moveToBench( data, i): void {
    this.dataService.addToReserves(data)

    // this.players.splice(i, 1);


}

  }

And finally the code for the bench.ts file...

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../app/data.service'
import { bench } from "../bench";

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

  moves: number = 5;
  btnText: string = "Make Starter";
  reserves: Array<any>;

  constructor(private dataService: DataService) { }

  getReserves() : void {
    this.dataService.getReserves()
      .subscribe(reserves => this.reserves = reserves);
  }

ngOnInit() {

      this.getReserves();
      // this.moveData();
  }

  makeStarter( data, i): void {
    this.dataService.addToStarter(data)

    // this.players.splice(i, 1);

}
}

I am looking to simply click a button in html to move the selected player to the sibling component. I am having trouble with how to structure the services/observable etc as this is my first time working with Angular.

I had a little free time ... so I moved your sample code to a stackblitz here: https://stackblitz.com/edit/angular-j2l8pq

I was not sure exactly what you were trying to accomplish, but tried to basically answer your question.

A few key things:

1) I assumed that the bench and the players arrays both needed to be of type Player . That allows you to move items of the same type between the two arrays without any loss of properties.

2) I changed the property in the component to be a getter. That way it would always get the current value from the service:

  get players(): Player[] {
    return this.dataService.players;
  }
  get bench(): Player[] {
    return this.dataService.bench;
  }

3) You did not seem to need a Subject/BehaviorSubject so I removed the imports.

I was not sure what "sibling component" you were referring to. But if you create another component that talks to the same service, if it also has a getter as shown above it will share the same data as the player component.

Hopefully the provided code provides the basic direction for you to answer your question.

Component

import { Component, OnInit } from "@angular/core";
import { DataService } from './player.service'
import { Player } from "./player";

@Component({
  selector: 'app-roster-box',
  template: 
    `<div>Current Roster</div>
    <li *ngFor="let player of players" (click)="moveToBench(player)">
      {{ player.name }}
    </li>
    <br>
    <div>Bench</div>
    <li *ngFor="let player of bench">
      {{ player.name }}
    </li>
    `
})
export class RosterBoxComponent implements OnInit {
  moves: number = 5;
  btnText: string = "Move to Bench";

  get players(): Player[] {
    return this.dataService.players;
  }
  get bench(): Player[] {
    return this.dataService.bench;
  }

  constructor(public dataService: DataService) {}

  getPlayers() : void {
    this.dataService.getPlayers()
      .subscribe();
  }

  ngOnInit() {
      this.getPlayers();
  }

  moveToBench( player ): void {
    console.log(player);
    this.dataService.addToReserves(player)
  }

}

Service

import { Injectable } from "@angular/core";
import { Player } from "./player";
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";

@Injectable()
export class DataService {

   players: Player[] = [];
   bench: Player[] = [];

    constructor() {}

    getPlayers(): Observable<Player[]> {
    this.players = [
            {
              index: 1,
              photo: "../../assets/images/lonzo.jpeg",
              name: "Lonzo Ball",
              position: "G",
              moves: 5
            },
            {
              index: 2,
              photo: "../../assets/images/Brook.jpeg",
              name: "Brook Lopez",
              position: "C",
              moves: 5
            }
          ]
      return of(this.players);
    }

    getReserves(): Observable<Player[]> {
      return of(this.bench);
    }

  addToReserves(player: Player) {
    this.bench.push(player);
    const index = this.players.indexOf(player);
    if (index > -1)
      this.players.splice(index, 1);
  }

  addToStarter(data) {
    this.players.push(data)
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM