Problems with Reactiveforms at Angular

Asked

Viewed 113 times

0

Hello, I’m having a hard time finding a solution to my problem so I’m here, I’m trying to create a search field on my page, it’s not doing the research, but it’s not returning any errors in the build or console, then I’m lost if I forgot some step or import of some module, I don’t know, help me please, follow the code:

servicos.service.ts

import {HttpClient, HttpParams} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';

import {Servico} from './servico/servico.model';
import {AUTONOMOUS_API} from '../app.api';

@Injectable()
export class ServicosService {

  constructor(private http: HttpClient) {}

  servicos(search?: string): Observable<Servico[]> {
    let params: HttpParams;
    if (search) {
      params = new HttpParams().append('q', search);
    }
    return this.http.get<Servico[]>(`${AUTONOMOUS_API}/autonomos/`, {params: params});
  }

  servicosById(id: string): Observable<Servico> {
    return this.http.get<Servico>(`${AUTONOMOUS_API}/autonomos/${id}/`);
 }
}

servicos.component.html

<div class="container">

  <div class="header-content" align="center">
     <h1>Catálogo de Serviços</h1>
     <br>

    <mdc-form-field [formGroup]="searchForm" fluid class="form">
      <mdc-text-field formControlName="searchControl" outlined label="Pesquisar" [mdcElevation]="3">
        <mdc-icon mdcTextFieldIcon leading>search</mdc-icon>
      </mdc-text-field>
    </mdc-form-field>
  </div>

  <div class="row">

  <div *ngFor="let servico of servicos" class="col-sm-4 col-xs-12">
    <app-servico [servico]="servico"></app-servico>
  </div>
</div>

</div>

servicos.component.ts

import { Component, OnInit } from '@angular/core';

import {Servico} from './servico/servico.model';
import {ServicosService} from './servicos.service';

import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
import {catchError, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {from} from 'rxjs';

@Component({
  selector: 'app-servicos',
  templateUrl: './servicos.component.html',
  styleUrls: ['./servicos.component.scss']
})
export class ServicosComponent implements OnInit {
  servicos: Servico[];

  searchForm: FormGroup;
  searchControl: FormControl;

  constructor(private servicosService: ServicosService,
              private fb: FormBuilder) { }

   ngOnInit() {
    this.searchControl = this.fb.control('');
    this.searchForm = this.fb.group({
      searchControl: this.searchControl
    });

    this.searchControl.valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(searchTerm => this.servicosService.servicos(searchTerm)
          .pipe(
            catchError(error => from([]))
          )
        )
      ).subscribe(dados => this.servicos = dados);

    this.servicosService.servicos().subscribe(dados => this.servicos = dados);

  }
}

app.modulets.

My app.module is great so I’ll send the main ones to Reactiveforms

// DEFAULT
import { NgModule } from '@angular/core';

import {CommonModule, HashLocationStrategy, LocationStrategy} from '@angular/common';

// COMPONENTS
import { AppComponent } from './app.component';
import { DialogLoginComponent } from './dialog-login/dialog-login.component';
import { DialogContateComponent } from './dialog-contate/dialog-contate.component';
// SERVICES
import {ServicosService} from './servicos/servicos.service';
// REACTIVE FORMS
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

@NgModule({
. . .
imports: [
  CommonModule,
  FormsModule,
  ReactiveFormsModule
],
providers: [
  ServicosService,
  {provide: LocationStrategy, useClass: HashLocationStrategy},
],
entryComponents: [
  DialogLoginComponent,
  DialogContateComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }

servicos.component.ts (UPDATED)

 import { Component, OnInit } from '@angular/core';

 import {Servico} from './servico/servico.model';
 import {ServicosService} from './servicos.service';

 import {FormBuilder, FormControl, FormGroup} from '@angular/forms';
 import {catchError, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
 import {from} from 'rxjs';

 @Component({
   selector: 'app-servicos',
   templateUrl: './servicos.component.html',
   styleUrls: ['./servicos.component.scss']
 })
 export class ServicosComponent implements OnInit {
  servicos: Servico[];

  searchForm = new FormGroup({
  searchControl: new FormControl('')
 });

  constructor(private servicosService: ServicosService,
              private fb: FormBuilder) { }

  ngOnInit() {
     this.searchForm = this.fb.group({
     searchControl: ['']
   });

    this.searchForm.get('searchControl').valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(searchTerm => 
this.servicosService.servicos(searchTerm)
          .pipe(
            catchError(error => from([]))
          )
         )
      ).subscribe(dados => this.servicos = dados);

    this.servicosService.servicos().subscribe(dados => this.servicos = dados);

  }

}

2 answers

0

  • Look at the end of the post already updated, does not work yet.

0

do so:

export class ServicosComponent implements OnInit {
  servicos: Servico[];
  searchForm: FormGroup;

    get search(){
    return this.searchForm.get('searchControl');
    }

  constructor(private servicosService: ServicosService,
              private fb: FormBuilder) { }

   ngOnInit() {
    this.searchControl = this.fb.control('');
    this.searchForm = this.fb.group({
      searchControl: ['']
    });

    this.search.valueChanges
      .pipe(
        debounceTime(500),
        distinctUntilChanged(),
        switchMap(searchTerm => this.servicosService.servicos(searchTerm)
          .pipe(
            catchError(error => from([]))
          )
        )
      ).subscribe(dados => this.servicos = dados);

    this.servicosService.servicos().subscribe(dados => this.servicos = dados);

  }
}
  • Here is not instantiating the searchControl, then when you call the this.searchControl of error.

  • Either you do get searchControl or this.search

  • still not working, take a look at the end of the post with the updated file

  • Is there an error in the console? See if in the network tab it is making the http call.

  • Well the console is normla no errors, just the angular production message, already in the network tab do not know exactly what you want me to see it makes call of the normal files by what I looked

  • Edit your question with the service code

  • Ready edited!

Show 2 more comments

Browser other questions tagged

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