как сделать так, чтобы данные формы ввода отображались в HTML - PullRequest
0 голосов
/ 24 апреля 2020

Эта ошибка должна быть простой, но я новичок с angular

Я считаю, что в этом коде должно быть мало изменений

Сервисный код ниже

import { Grade } from './../calculator/calculator.model';
import { Injectable } from '@angular/core';
import { Input } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ResultService {
  @Input()
  grade: Grade = {
    name: '',
    grade1: null,
    grade2: null,
    grade3: null,
  };

  calcGrade(): void {
    let nota1 = this.grade.grade1 * 0.25;
    let nota2 = this.grade.grade2 * 0.25;
    let nota3 = this.grade.grade3 * 0.5;

    let conta = nota1 + nota2 + nota3;

    if (conta < 6.2) {
      console.log(
        `o aluno ${this.grade.name} foi reprovado com a nota ${conta}`
      );
    }
    if (conta >= 6.2) {
      console.log(
        `o aluno ${this.grade.name} foi aprovado com a nota ${conta}`
      );
    }
  }

  constructor() {}
}

, когда я нажимаю на кнопку, я хочу вызвать этот компонент с данными, введенными в другом компоненте

HTML Код ниже

Или я могу добавить код службы в компонент TS

<div class="container">
  <div class="content">
    <h1>
      o aluno {{ grade.name }} tirou {{ grade.grade1 }} na primeira prova e
      {{ grade.grade2 }} na segunda prova
    </h1>
  </div>
</div>

Код HTML из компонент сильфонный

<div class="container">
  <div class="header">
    Olá Professor
  </div>
  <form class="form" action="submit">
    <input
      [(ngModel)]="grade.name"
      name="name"
      type="text"
      class="inputName"
      placeholder="Nome do Aluno:"
    />
    <input
      [(ngModel)]="grade.grade1"
      name="grade1"
      type="number"
      class="inputGrade"
      placeholder="Nota da prova 1:"
    />
    <input
      [(ngModel)]="grade.grade2"
      name="grade2"
      type="number"
      class="inputGrade"
      placeholder="Nota da prova 2:"
    />
    <input
      [(ngModel)]="grade.grade3"
      name="grade3"
      type="number"
      class="inputGrade"
      placeholder="Nota da prova 3:"
    />
    <a routerLink="/result">
      <button (click)="calcGrade()" class="button">
        Calcular
      </button>
    </a>
  </form>
  <div>
    <router-outlet></router-outlet>
  </div>
</div>

1 Ответ

0 голосов
/ 25 апреля 2020

Службу и объект поведения можно использовать для передачи данных между компонентами.

Допустим, вам необходимо передать оценку от компонента A к компоненту B при нажатии какой-либо кнопки в компоненте A

* 1004. * мы можем определить этот субъект поведения в сервисе, , когда вы нажимаете эту кнопку в компоненте A, просто выбрасываете или вводите информацию о классе, введенную В компоненте B в хуке ngOnInit мы можем подписаться на эту тему поведения, чтобы получить информацию об этом классе

в сервисе

// define a new behavior subject to transfer the grade from component A to component B
gradeSubject = new BehaviorSubject<Grade>(null); // set the initial value of this behavior subject to null, you can set it anything you need

в компоненте A

  constructor(private resultService: ResultService) {} // inject the service in component A

  onClick(gradeInput) {
    // gradeInput is an object contains all the properties of the grade
    // design it as you want, maybe you pass name, grade1, grade2, and grade3 manually
    // the most important thing, that we need to pass this object through the behavior subject

    this.resultService.gradeSubject.next(gradeInput);
  };

-и в компоненте B

  grade: Grade; // this is the grade object you used in the html

  constructor(private resultService: ResultService) {}

  ngOnInit() {
    // subscribe the behavior subject from the service to get the grade object

    this.resultService.gradeSubject.subscribe((gradeResult: Grade) => {
      // set the grade property in this component to the gradeResult
      this.grade = gradeResult;
    });

  }

надеюсь, что это поможет



Обновление

после проверки ваших кодов, вот решение с использованием субъекта поведения, как описано выше

- сохранить тему поведения, определенную в сервисе

- В calculator.component.ts мы выберем или добавим оценку предмету поведения, определенному в сервисе, сделаем это в calcGrade метод, как в этом методе Если мы перейдем к компоненту результатов

calcGrade(): void {
  let nota1 = this.grade.grade1 * 0.25;
  let nota2 = this.grade.grade2 * 0.25;
  let nota3 = this.grade.grade3 * 0.5;

  let conta = nota1 + nota2 + nota3;

  if (conta < 6.2) {
    console.log(`o aluno ${this.grade.name} foi reprovado com a nota ${conta}`);
    // this.router.navigate(['/result']);
  }
  if (conta >= 6.2) {
    console.log(`o aluno ${this.grade.name} foi aprovado com a nota ${conta}`);
    // this.router.navigate(['/result']);
  }

  // here we will emit the grade to the behavior subject
  this.resultService.gradeSubject.next(this.grade);
  this.router.navigate(['/result']); // just do the navigation one time here rather than doing it in all the conditions
}

- в results.component.ts, мы подпишемся на объект поведения, чтобы получить объект оценки

  ngOnInit() {
    // here we need to subscribe to that behavior subject
    this.resultService.gradeSubject.subscribe((res: Grade) => {
      this.grade = res;
    });
  }
...