How to write to the mongodb API

1

I have this API (Controller)

[Produces("application/json")]
[Route("api/[controller]")]
public class TypesFieldsController : Controller
{
        private IAddTypeFieldService addTypeFieldService;

        public TypesFieldsController(IAddTypeFieldService addTypeFieldService)
        {
            this.addTypeFieldService = addTypeFieldService;
        }

        //[Authorize("Bearer")]
        [AllowAnonymous]
        [HttpPost (Name ="PostTypeField")]
        public async Task<IActionResult> PostTypeField([FromBody] TypeFieldRequest typeFieldRequest)
        {
            AddTypeFieldCommand addTypeFieldCommand = new AddTypeFieldCommand(typeFieldRequest.Name);
            AddTypeFieldResult addTypeFieldResult = await this.addTypeFieldService.Process(addTypeFieldCommand);

            TypesFieldsDetailsModel typesFieldsDetailsModel = new TypesFieldsDetailsModel(addTypeFieldResult.TypeField.TypeFieldId, addTypeFieldResult.TypeField.Name);

            return new ObjectResult(typesFieldsDetailsModel);
        }

    }

And also this model

public class TypeField : Entity, IAggregateRoot
    {
        public string Name { get; private set; }

        public int Version { get; set; }

        public TypeField(string name)
        {
            this.Name = name;
        }
    }

Well, what I need now would be to get my form HTML and save it to the mongo. This is my HTML and the submit button. That's why I need to give POST .

<div class="container">
  <form role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div></div>

    <div class="required-field-block">
        <input type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <div class="required-field-block">
        <input type="text" placeholder="Versão" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <button class="btn btn-primary">Criar</button>
</form>
</div> 

And this is the ADD method of my service. I just do not understand where ItemName comes from and how I pass an form .

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

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

How do I give a post with the html above using Angular 6?

EDIT1 I did it: Component

export class CreateTypeFieldsComponent implements OnInit {

  private _createTypesFields: Model.CreateTypesFields;
  private form: FormGroup;

  constructor(private _createTypeService: CreateTypeFieldsService, private builder: FormBuilder) {

  }      

  ngOnInit() {

      this._createTypeService.postCreateTypeFields(this._createTypesFields)
      .subscribe( success => {
        if(success.Result){
          //anything here
        }
      },
      error =>{
      }
    );

    this.form = this.builder.group({
      nome: '',
      versao: ''
    }) 
  }

and in html I have this

<div class="container">
  <form [formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div class="required-field-block">
        <input formControlName="nome" type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <div class="required-field-block">
        <input formControlName="versao" type="text" placeholder="Versão" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>    
    <button type="submit" class="btn btn-primary" >Criar</button>
</form>
</div>

When I get this error, when debugging in the browser:

  

Can not bind to 'formGroup' since it is not a known property of 'form'.   ("] [formGroup]=" form "   (ngSubmit)="add (form.value)" role="form" style="width: 400px; margin: 0   auto; ""): ng: ///AppModule/CreateTypeFieldsComponent.html@1: 8 No   provider for ControlContainer ("[ERROR   - >]

EDIT2

Well, with the help of my colleagues below, I have been able to resolve the errors but not yet write, but the Insert in Mongodb is called because the ID (GUID in MonoDB) that I press the Create button. It turns out that the Name field is empty and I think it has to do with the form I'm sending. Here are the changes I made and I deleted the errors: Component

import { Component, OnInit, ModuleWithProviders } from '@angular/core';
import { FormControl,FormBuilder, FormGroup, NgControl } from '@angular/forms';
import { CreateTypeFieldsService } from '../create-type-fields.service';

@Component({
  selector: 'app-create-type-fields',
  templateUrl: './create-type-fields.component.html',
  styleUrls: ['./create-type-fields.component.css'],
  providers: []
})
export class CreateTypeFieldsComponent implements OnInit {

  createForm = new FormGroup({
    Name: new FormControl
  })

  private _createTypesFields: Model.CreateTypesFields;
  private form: FormGroup;

  constructor(private _createTypeService: CreateTypeFieldsService, private builder: FormBuilder) { 

     this.form = this.builder.group({
      Name: ''
    }) 
  } 
  ngOnInit() { }

    onPostCreateTypeFields(){
      this.createForm.value;
      this._createTypeService.postCreateTypeFields(this._createTypesFields)
          .subscribe( success => {
            if(success.Result){
              //anything here
            }
          },
          error =>{
          }
        );
      }
    }

Service

import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Configuration } from './app.constants';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

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

  private actionUrl: string;
  private url: 'http://localhost:56758/api';

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

    public postCreateTypeFields(itemName: Model.CreateTypesFields): Observable<any> {

      const toAdd = JSON.stringify({ ItemName: itemName });

      return this.http.post(this.actionUrl, toAdd, httpOptions);
  }
}

HTML

<div class="container">
  <form [formGroup]="createForm" (ngSubmit)="onPostCreateTypeFields()" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div class="required-field-block">
        <input formControlName="Name" type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary" >Criar</button>
</form>
</div>

When I write (create) the Name field comes null in MongoDB. See below for Postman

{
    "error": false,
    "itens": [
       {
            "typeFieldId": "0faca34a-8a52-4f03-911a-cedc6f3e7b0c",
            "name": null
        },
        {
            "typeFieldId": "a074125d-4fe0-429b-a811-d148881e8036",
            "name": null
        },
        {
            "typeFieldId": "880dc3e6-38d0-44ad-b261-7da50b593fb6",
            "name": null
        },
        {
            "typeFieldId": "90211c1e-298e-4919-a043-2ee45885e7aa",
            "name": null
        },
        {
            "typeFieldId": "19261221-e822-498d-9265-a51fc69224a8",
            "name": null
        },
        {
            "typeFieldId": "8b19100e-07ef-4fff-8053-7475ffeb4325",
            "name": null
        },
        {
            "typeFieldId": "a4f4fbf5-737c-4089-bdb1-649599a9be6e",
            "name": null
        },
        {
            "typeFieldId": "b5746f34-28b0-4e17-8ab9-13113632d942",
            "name": null
        },
        {
            "typeFieldId": "d5a21f36-a33c-46cc-961d-edd1c1fc76aa",
            "name": null
        },
        {
            "typeFieldId": "075a556c-8633-43aa-9ee8-0aa955c85229",
            "name": null
        },
        {
            "typeFieldId": "c48c9287-26c5-4e88-8dcc-3129ba241122",
            "name": null
        },
        {
            "typeFieldId": "746252ae-d72a-4bbb-ac6a-a72aff9dcf55",
            "name": null
        },
        {
            "typeFieldId": "2c5e6e2b-9df4-4077-8dba-561479b929e5",
            "name": null
        },
        {
            "typeFieldId": "9723de60-8172-47f9-baa9-d4ba25ba5bad",
            "name": null
        },
        {
            "typeFieldId": "d2ce0c2d-f352-4007-bbcf-92ed3236ddc0",
            "name": null
        },
        {
            "typeFieldId": "294f3233-2fbe-4e25-818e-fed5336d5a28",
            "name": null
        },
        {
            "typeFieldId": "e19e6dbf-ac96-4170-8e80-5a0fac28c924",
            "name": null
        },
        {
            "typeFieldId": "401c6eb1-8876-4b34-b847-709c3a956dee",
            "name": null
        },
        {
            "typeFieldId": "bd851785-1f37-48ca-8bbe-5f34eb29ba13",
            "name": null
        },
        {
            "typeFieldId": "b3f628bf-9bcb-4b55-9cbb-aab18f64e72d",
            "name": null
        }
    ],
    "message": ""
}

EDIT3

Well, my service looks like this:

public postCreateTypeFields(itemName: Model.CreateTypesFields): Observable<any> {
   return this.http.post(this.actionUrl, itemName, httpOptions);
}

I changed the Name property to name, actually looking at the API by Swagger, he expected a name and not Name , the problem is that Postman it has accepted Name instead of name. It's okay

    
asked by anonymous 16.07.2018 / 15:43

2 answers

1

In your case the itemName you are only receiving a string, then it will not be the integer form.

Create a formGroup as follows:

  <form [formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

No typescript make the form as follows:

constructor(private builder: FormBuilder)
form: FormGroup;

 this.form = this.builder.group({
      nome: '',
      versao: ''
})

And then add to your inputs:

<input formControlName="versao" type="text" placeholder="Versão" class="form-control">
<input formControlName="nome" type="text" placeholder="Nome" class="form-control">

After this inside your post can be done as follows:

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

    return this.http.post<T>(this.actionUrl, toAdd);
}
    
16.07.2018 / 16:23
1

It seems like you forgot to import the reactiveFormsModule where you declare your component.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule 
  ],
  declarations:[
      seuComponente
   ]
    
17.07.2018 / 12:12