Update(Put) on my project does not write to BD(Mongodb)

Asked

Viewed 20 times

1

I need to make an editing screen and I’m not getting it. See how my Component is doing(I’ve eliminated Imports to save space)

@Component({
  selector: 'app-operators',
  templateUrl: './operators.component.html',
  styleUrls: ['./operators.component.css'],
  providers: [OperatorService]
})

export class OperatorsComponent implements OnInit {

  displayedColumns: string[] = ['codigo', 'nome'];
  private operUrl: 'api/Operators';

  public message: string;
  public dataSource: Model.Itens[];
  createForm :FormGroup;

  public form:any;


  constructor(private _operService: OperatorService, private builder: FormBuilder) {
  }

  ngOnInit() {

    this.onGet();
  }

  onDelete(operator: Model.Itens) {
    debugger;
    if (confirm('Deseja excluir o operador: ' + operator.name + '?')) {

      this._operService
        .delete<any>(operator.operatorId)
        .subscribe((res) => {
          this.onGet();
        });
    }
  }

  onGet() {
    this._operService
      .getAll<Model.Result<Model.Itens>>()
      .subscribe((data: Model.Result<Model.Itens>) => {
        debugger;
        this.dataSource = data.itens;
      });
  }

  initEditOperator(operator: any){
    operator.edit = true;
    this.form = this.builder.group({
      id: operator.id,
      name: operator.name
    });
  }

  checkEdit() {
    if (this.dataSource == null || this.dataSource.length == 0) return false;
      return this.dataSource.filter((item: any) => item.edit === true).length == 0;
  }

  onUpdate(){

    this._operService.update<Model.Result<Model.Itens>>(this.form.id, this.form.name)
    .subscribe(success =>{
        // if(success.Result){

        // }
      },
        error =>{
      } 
    );

  }
}

this is the html

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped table-bordered table-hover">
                <caption>Lista de Operadores</caption>
                <thead class="thead-dark">
                    <tr>
                        <th>Código</th>
                        <th>Nome</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let operator of dataSource">
                        <form *ngIf="operator.edit != true">
                            <td>{{ operator.operatorId}}</td>
                            <td>{{ operator.name }}</td>
                            <td>
                                <fa *ngIf="checkEdit()" name="pencil" (click)="initEditOperator(operator)"></fa>
                            </td>
                            <td>
                                <fa *ngIf="checkEdit()" name="times" (click)="onDelete(operator)"></fa>
                            </td>
                        </form>
                        <div *ngIf="operator.edit === true">
                            <td> {{ operator.operatorId}}<input type="hidden" [(ngModel)]="operator.operatorId"></td>
                            <td> <input type="text" [(ngModel)]="operator.name"></td>
                            <td>
                                <fa name="save" (click)="onUpdate()"></fa>
                            </td>
                            <td>
                                <fa name="ban" (click)="operator.edit = null;"></fa>
                            </td>
                        </div>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

The call on HTML is in the (Onclick)=onUpdate()

This is my service

@Injectable({
  providedIn: 'root'
})
export class OperatorService {

  private actionUrl: string;

    constructor(private http: HttpClient, private _configuration: Configuration) {
        this.actionUrl = _configuration.ServerWithApiUrl + 'Operators/';
    }

    public getAll<T>(): Observable<T> {
      return this.http.get<T>(this.actionUrl);
  }

  public getSingle<T>(id: number): Observable<T> {
      return this.http.get<T>(this.actionUrl + id);
  }

  public add<T>(itemName: string): Observable<T> {
      const toAdd = JSON.stringify({ ItemName: itemName });

      return this.http.post<T>(this.actionUrl, toAdd);
  }

  public update<T>(id: string, itemToUpdate: any): Observable<T> {
      return this.http
          .put<T>(this.actionUrl + id, JSON.stringify(itemToUpdate));
  }

  public delete<T>(id: string): Observable<T> {
      return this.http.delete<T>(this.actionUrl + id);
  }
}

@Injectable()
export class CustomInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        console.log(JSON.stringify(req.headers));
        return next.handle(req);
    }
}

My Model

declare namespace Model{
    export interface Result<T>{
        error: boolean,
        itens: Array<T>,
        message: string
    }

    export interface Itens{
        operatorId: string,
        name: string,
    }
}

I can see the changes on the screen and everything, but when I give a F5 on the page, back to the way it was, it’s due to not write in the database. I use Mongodb, but what’s happening has nothing to do with Mongo, so I didn’t add his tag.

When I call the routine, debugging in the browser, I have this mistake

PUT http://localhost:56758/api/Operators/Undefined 404 (Not Found)

  • Puts a.log() console inside your update method to see if the parameter is coming Undefined. At some point you are losing the value of your parameter, so you are Undefined on the route.

  • The not found I understood, but I can’t record. When I put one formControl in html, make fun of everything. I am reading the documentation of formControl and understand its use, but lack an understanding to complete the task that was to have completed.

  • @Gabrielamendonça, thanks for the tip. I will do this yes and put the result.

  • @pnet, it worked?

  • I haven’t tried it yet because I need to finish other canvases first, but I believe by the end of the day I test.

No answers

Browser other questions tagged

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