Firebase показать данные в выбранной форме - угловой - PullRequest
0 голосов
/ 03 ноября 2019

Я пытаюсь показать данные в выбранной форме, из таблицы героев и "nombre" это имя клиента.

Во второй таблице я хочупокажите их при добавлении продуктов, чтобы приписать им клиентов.

Может ли кто-нибудь помочь мне в этом? Я новичок в angular:)

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { HeroesService } from '../../services/heroes.service';
import { HeroeModel } from '../../models/heroe.model';
import {AngularFireDatabase } from 'angularfire2/database';

import Swal from 'sweetalert2';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: HeroeModel[] = [];
  cargando = false;

  constructor(private heroesService: HeroesService) {}

  ngOnInit() {
    this.cargando = true;
    this.heroesService.getHeroes().subscribe(resp => {
      this.heroes = resp;
      this.cargando = false;
    });
  }

  borrarHeroe(heroe: HeroeModel, index: number) {
    Swal.fire({
      title: 'Uwaga!',
      text: `Czy chcesz trwale usunąć kontrahenta ${heroe.nombre}?`,
      type: 'warning',
      showConfirmButton: true,
      showCancelButton: true
    }).then(resp => {
      if (resp.value) {
        this.heroesService.deleteHeroe(heroe.id).subscribe(resp => {
          this.heroes.splice(index, 1);
        });
      }
    });
  }
}

add-products.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import Swal from 'sweetalert2';
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { ADDProductsModel } from 'src/app/models/add-products.model';
import { ProductsService } from 'src/app/services/products.service';
import { HeroesComponent } from 'src/app/pages/heroes/heroes.component';
import { HeroeComponent } from 'src/app/pages/heroe/heroe.component';

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

  ADDProducts: ADDProductsModel = new ADDProductsModel();

  constructor(
    private ProductsService: ProductsService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');

    if (id !== 'new') {
      this.ProductsService.getADDProducts(id).subscribe((resp: ADDProductsModel) => {
        this.ADDProducts = resp;
        this.ADDProducts.id = id;
      });
    }
  }

  guardar(form: NgForm) {
    if (form.invalid) {
      console.log('Nieprawidłowy format');
      return;
    }

    Swal.fire({
      title: 'Ładowanie',
      text: 'Trwa zapis...',
      type: 'info',
      allowOutsideClick: false
    });

    Swal.showLoading();

    let peticion: Observable<any>;

    if (this.ADDProducts.id) {
      peticion = this.ProductsService.actualizarADDProducts(this.ADDProducts);
    } else {
      peticion = this.ProductsService.crearADDProducts(this.ADDProducts);
    }

    peticion.subscribe(resp => {
      Swal.fire({
        title: this.ADDProducts.number,
        text: 'Dodano pomyślnie',
        type: 'success'
      });
    });
    console.log(form);
    console.log(this.ADDProducts);
  }
}

1 Ответ

0 голосов
/ 08 ноября 2019
  • Во-первых, Рассмотрим модель общения между родителем и ребенком при взаимодействии компонентов. Для простоты я не собираюсь включать какую-либо часть Firebase здесь. Я предполагаю, что вы работаете с Firebase Data очень хорошо.

Теперь ваша проблема заключается в том, как отправить данные обратно от ребенка к родителю, поэтому вот ваше решение.

Полное решение можно найти здесь StackBlitz Link

  • app.component.html

     <div>
          <span > Name comes form child in Parent Component </span>
          <select>
              <option> Select Name </option>    
              <option *ngFor="let item of nameFromChild"> {{item}} </option>
          </select>
     </div>
    
  • app.component.ts

     export class AppComponent  {
            nameFromChild: string[] = []; // your property.
            /*
                nameFromChildFun() is called when there is data emitted from child-component. 
                @parms ='nameFromChild' : gets parameter from child using $event from app.component.html.
            */
            nameFromChildFun(nameFromChild){
                   this.nameFromChild.push(nameFromChild); //name pushes to property. and displaying in select tag using *ngFor. 
            }
     }
    
  • child.component.html

     <input type ="text" [(ngModel)]="name"> <br><br>
     <button (click)="sendNameToParent(name)"> Add Name to Parent </button>
    
  • child.component.ts

     import { Component, EventEmitter, Output } from '@angular/core';
    
     export class ChildComponent implements OnInit {
            @Output() nameFromChild = new EventEmitter();
            // nameFromChild is passed in app.component.html in <app-child (nameFromChild)="nameFromChildFun($event)
    
            sendNameToParent(name){
                 this.nameFromChild.emit(name); // emitting value to parent.
            }
     }
    
  • Теперь, когда пользователь нажимает Затем нажмите кнопку addNameToParent для childComponent, затем вызовите службу Firebase, чтобы сначала сохранить или обновить данные, а затем загрузите эти данные в родительский app.component.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...