简体   繁体   English

在 Angular 中使用响应式表单与服务

[英]Using reactive forms in Angular with services

i'm tryng to make a kind of deckBuilder, i have some cards and decks made of cards, these are the card and deck models我正在尝试制作一种deckBuilder,我有一些卡片和卡片制作的卡片,这些是卡片和卡片模型

export class Card {
  public name: string;
  public manaCost: number;
  public imagePath: string;

  constructor(name: string, manaCost: number, imagePath: string) {
    this.name = name;
    this.manaCost = manaCost;
    this.imagePath = imagePath;
  }
}

and deck和甲板

import { Card } from '../card/card.model';

export class Deck {
  public deckName: string;
  public deckClass: string;
  public deckCards: Card[];

  constructor(deckName: string, deckClass: string, deckCards: Card[]) {
    this.deckName = deckName;
    this.deckClass = deckClass;
    this.deckCards = deckCards;
  }
}

this is the deckService file这是deckService文件

import { Deck } from './deck.model';
import { Card } from '../card/card.model';


export class DeckService {

  decks: Deck[] = [

    new Deck("Control Priest", "Priest", [
      new Card("Reno Jackson", 6, "../../assets/img/Reno_Jackson.png"),
      new Card("Abomination", 5, "../../assets/img/Abomination.png"),
      new Card("Blade Flurry", 4, "../../assets/img/Blade_Flurry.png"),
      new Card("Felfire Potion", 6, "../../assets/img/Felfire_Potion.png")
    ]),
    new Deck("Big Spell Mage", "Mage", [
      new Card("Reno Jackson", 6, "../../assets/img/Reno_Jackson.png"),
      new Card("Abomination", 5, "../../assets/img/Abomination.png"),
      new Card("Blade Flurry", 4, "../../assets/img/Blade_Flurry.png"),
      new Card("Felfire Potion", 6, "../../assets/img/Felfire_Potion.png")
    ])
  ];

  newDeck: Deck; // this is undefined when i try to log it


  constructor() {

  }

  getDecks() {
  return this.decks.slice();
}

  addCard(card: Card){
    console.log(this.newDeck)       // why can't access to newDeck? i have to 
                                    //    bind this function? if i log 'this'  
                                    //   i get DeckService as expected
    this.newDeck.deckCards.push(card);

}

addNewDeck(deck: Deck){
  console.log(this.decks);
  this.decks.push(deck);
};

}

i have a reactive form in which i can add cards to a deck choosing the card with a selection, i want to use the newDeck to save the cards from the form and then push the newDeck in the decks array, but newDeck is undefined, is this a binding problem?我有一个反应式形式,我可以在其中将卡片添加到带有选择的卡片中,我想使用 newDeck 从表单中保存卡片,然后将 newDeck 推送到卡片数组中,但是 newDeck 未定义,是这是一个绑定问题? this is the form .ts file where i use the deckservice这是我使用deckservice的.ts文件格式

import { Deck } from './../deck/deck.model';
import { DeckService } from "./../deck/deck.service";

import { Component, OnInit } from "@angular/core";
import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms";
import { CardService } from "../card/card.service";
import { Card } from "../card/card.model";
import { Observable } from "rxjs";

@Component({
  selector: "app-create-deck",
  templateUrl: "./create-deck.component.html",
  styleUrls: ["./create-deck.component.scss"]
})
export class CreateDeckComponent implements OnInit {
  cards: Card[];
  classes = [
    "Priest",
    "Mage",
    "Shaman",
    "Rogue",
    "Warrior",
    "Warlock",
    "Druid",
    "Paladin"
  ];

  createDeckForm: FormGroup;
  deckName: FormControl;

  constructor(
    private cardService: CardService,
    private deckService: DeckService
  ) {}

  ngOnInit() {
    this.cards = this.cardService.getCards();
    this.createDeckForm = new FormGroup({
      deckName: new FormControl("Meme Deck"),
      deckClass: new FormControl(),
      deckCards: new FormControl()
    });
  }

    onAddCard(){
      this.deckService.addCard(this.createDeckForm.value);     //this is wrong but the problem is that i can't access to newDeck


    }

  onSubmit() {

    this.deckService.addNewDeck(this.createDeckForm.value);

  }
}

By经过

newDeck: Deck;

you just declare the member, but don't initialize it.您只需声明该成员,但不要对其进行初始化。 Therefore its value is undefined .因此它的值是undefined Use:用:

newDeck: Deck = new Deck(....); // .... are correct values according to its constructor.

instead.反而。

Additionally have a look at this:https://dev.to/satansdeer/typescript-constructor-shorthand-3ibd另外看看这个:https ://dev.to/satansdeer/typescript-constructor-shorthand-3ibd

Inside your deck.service.ts in line 23 in stackblitz you could usedeck.service.ts的第 23 行中的deck.service.ts 中,您可以使用

newDeck: Deck = this.decks[0];

alternatively and it would work, too.或者,它也会起作用。

thanks, i don't know if i have to open another question but i have another problem, this is the .html of the form谢谢,我不知道我是否必须提出另一个问题,但我有另一个问题,这是表单的 .html



<div class="container">
  <div class="row">
    <form [formGroup]="createDeckForm" (ngSubmit)="onSubmit()">

      <label >Deck Name</label>
      <input
        type="text"
        id="deckName"
        formControlName="deckName"
        class="form-control"
      />
      <p>

      </p>
      <hr>
      <label for="deckClass">Deck class</label>
      <select id="deckClass" formControlName="deckClass">
        <option
            *ngFor="let class of classes"
            [value]="class">
            {{class}}
      </option>
      </select>
      <hr>
      <label for="deckCards">Select a Card</label>
      <select formControlName = "deckCards" id="deckCards" name="deckCards">
        <option
            *ngFor="let card of cards"
            [ngValue]="card">
            {{card.name}}
      </option>
    </select>

      <button (click) = "onAddCard()" class="btn btn-primary">Add Card</button>
      <hr>
      <button class="btn btn-primary" type="submit">Submit</button>

    </form>
  </div>
</div>

i have 2 buttons, one for adding cards to the deck and the onSubmit one to add the deck in the deck array but when i click on the addCard one it is like i'm pressing the submit one too我有 2 个按钮,一个用于向牌组中添加卡片,一个用于在牌组数组中添加牌组,而 onSubmit 一个用于在牌组阵列中添加牌组,但是当我点击 addCard 一个时,就像我也在按下提交一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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