Angular 6 - Reactive Forms - load observable after clicking on the form

Asked

Viewed 189 times

0

form has been button then I post, and only returns when I click on the form formcontrolname

import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NavParams } from '@ionic/angular/dist/directives/navigation/nav-params';
import { Observable, Subscription } from 'rxjs';
import { MatTableDataSource, MatPaginator, MatSort, MatRadioChange } from '@angular/material';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ApiProvider } from '../../providers/api';
import { ModalController } from '@ionic/angular/dist/providers/modal-controller';
import { AlertController, LoadingController } from '@ionic/angular';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-ticket',
  templateUrl: './ticket.component.html',
  styleUrls: ['./ticket.component.scss']
})
export class TicketComponent implements OnInit, OnDestroy {

  dataSource: MatTableDataSource<any>;
  orderService: Observable<any>
  displayedColumns: string[] = ['select','tipo','situacao','numos','dhchamada' ];
  formOS: FormGroup;
  rowOS: any;
  subOS: Observable<any> = undefined
  sub: Subscription[] = [];
  currentUser: any
  filteredReason: Observable<any>
  filteredExecutant: Observable<any>
  filteredStatus: Observable<any>
  filteredService:  Observable<any>
  currentContract: any
  addSubOS = false;
  radio

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private nav: NavParams,
    private _formBuilder: FormBuilder,
    private api: ApiProvider,
    private modal: ModalController,
    private alertCtrl: AlertController,
    private loadingCtrl: LoadingController
  ) {

    this.formOS = this._formBuilder.group({
      numos: ['', Validators.required],
      numcontrato: ['', Validators.required],
      codserv: ['', Validators.required],
      reason: ['', Validators.required],
      status: ['', Validators.required],
      executant: ['',Validators.required],
      solucao: ['',Validators.required]
    })

   }

  ngOnInit() {




    this.sub.push(this.api.getCurrentUser().subscribe(
      (data) => { this.currentUser = data[0] },
      (error) => console.log(error),
      () => console.log('completou'),
    ))

    this.sub.push(this.api.getCurrentContract().subscribe(
      (data) => this.currentContract = data,
      (error) => console.log(error),
      () => console.log('completou')
    ))



    this.sub.push(this.formOS.get('codserv').valueChanges.
    pipe(
      debounceTime(300)
    ).
    subscribe( (s) =>{
      if(s){
        this.filteredReason = this.api.findReason(s);
        this.filteredExecutant = this.api.findExecutant(s);
        this.filteredStatus = this.api.findStatus(s);
      }

    }))


    this.orderService = this.nav.get('value');
    this.sub.push(this.orderService.subscribe( 

      (data) => { this.dataSource = new MatTableDataSource(data.success),
        setTimeout(() => { this.dataSource.paginator = this.paginator,   this.dataSource.sort = this.sort }); 

        console.log(this.dataSource)},
      (error) => console.log(error),
      () => console.log('completou'),
    ))


  }

  public applyFilter(value: string){
    this.dataSource.filter = value.trim().toLowerCase();
  }

  selectedOS(row){
    this.rowOS = row
    if(row){
      this.formOS.patchValue({
        numos: row.numos,
        numcontrato: this.currentContract.numcontrato
      })
      this.subOS = this.api.findSubOS(row.numos)
      this.showGenerate(row)
    }
  }

  removeRowSelected(){
    this.rowOS = undefined
    this.subOS = undefined
    this.addSubOS = false
    this.formOS.reset()
    this.formOS.get('codserv').setValue(undefined)
    this.radio = undefined

  }

  closeModal(){
    this.modal.dismiss()
  }

showGenerate(row){
  if(row.tipo === 'CLIENTE' && row.situacao === 'P'){
    this.filteredService = this.api.findService(this.currentContract.numcontrato)
    this.addSubOS = true
  }
}

private async showAlert() {

  const alert = await this.alertCtrl.create({
    header: 'Confirmar geração da subOS',
    message: `para a Ordem de Serviço: ${this.rowOS.numos}`,
    buttons: [
      {
        text: 'Cancelar',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('Confirm Cancel');
        }
      }, {
        text: 'Sim',
        handler: () => {
          this.generateSubOS(this.formOS.value, this.currentUser.codusu)
        }
      }
    ]
  });

  await alert.present();
}

submit(){
 if(this.formOS.valid){
    this.showAlert()
 }
}


public generateSubOS(form, codusu){


   this.api.generateSubOS(form, codusu).subscribe(
      (data) => {
       if(data.hasOwnProperty('success')){ 
        this.formOS.get('codserv').setValue(undefined)
        this.formOS.reset()
        this.selectedOS(this.rowOS)
        this.api.setMessage(data.success,'success')  
       }else{
         this.selectedOS(this.rowOS)
         this.api.setMessage(data,'danger')
       }
     },
     (error) => { console.log(error)} ,
     () => {  console.log('completou')   }, 
   )
}

private async showLoading() {
  const loading = await this.loadingCtrl.create({
     spinner: 'crescent',
     message: 'Limpando os formulários',
     duration: 5000
  })

  return await loading.present()
}


ngOnDestroy() {
    this.sub.forEach((s) => {
      s.unsubscribe()
    })
    this.addSubOS = false
 }

}
  • 1

    Jonathan welcome to the stack overflow, please post the code relating to your question.

  • Note: If I use the alt tab, async works

  • take a look at the button if it is type="Submit" in your html template

  • button is outside the <form> tag, I managed to resolve... this.nameField.nativeElement.Focus()

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.