I wanted to add new record to my MSSQL database with my Angular SPA, but when I send the form I got nothing but just error 400 - Bad Request. I think it's only SPA fault, because everything is working just fine when I test it with Postman.
My POST body should look like this:
{
"Nazwa": "String",
"Opis": "Another String",
"Ownerusername": "Another String",
"Ends": "1976-07-28"
}
So I made a simple model in my eventcreator.component.ts:
import { Component, OnInit } from '#angular/core';
import { EventService } from '../_services/evncreator.service';
declare let alertify: any ;
#Component({
selector: 'app-eventcreator',
templateUrl: './eventcreator.component.html',
styleUrls: ['./eventcreator.component.css']
})
// declare let alertify;
export class EventcreatorComponent implements OnInit {
model: any = [];
constructor(private evntservice: EventService) {}
ngOnInit() {}
evnCreate() {
// this.model = JSON.parse(this.model);
this.evntservice.eventCreate(this.model).subscribe(
() => {
alertify.success('Utworzono wydarzenie');
},
error => alertify.error('Wystąpił błąd')
);
console.log(this.model);
}
evnAbort() {
window.location.href = '/';
}
}
This script is using evntservice.component.ts, so I want to attach it too:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { JwtHelperService } from '#auth0/angular-jwt';
#Injectable({
// dekorator
providedIn: 'root'
})
export class EventService {
constructor(private http: HttpClient) {}
eventCreate(model: any) {
return this.http.post('http://localhost:5000/api/Events', model);
}
}
My eventcreator.component.html is looking like this:
<form #registerForm="ngForm" (ngSubmit)="evnCreate()">
<div class="content p-3 ml-4 mr-4 bg-white">
<h1 class="display-2 text-dark text-center">Kreator wydarzeń</h1>
</div>
<div class="content">
<div class="content ml-4 mr-4 p-3 bg-warning">
<h1 class="ml-2 mt-4 mb-4 text-center">Nazwa wydarzenia:</h1>
<input
class="form-control mt-3 mb-3 p-lg-4 "
[(ngModel)]="model.Nazwa"
name="Nazwa"
required
/>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Opis wydarzenia:</h1>
<textarea
class="form-control mt-3 mb-3 p-lg-4"
required
[(ngModel)]="model.Opis"
name="Opis"
></textarea>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Data wydarzenia:</h1>
<input
type="text"
class="form-control"
required
name="Ends"
[(ngModel)]="model.Ends"
/>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Organizator:</h1>
<input
class="form-control text-success mt-3 mb-3 p-lg-4 "
required
name="Ownerusername"
[(ngModel)]="model.Ownerusername"
/>
<div class="text-center">
<button
type="submit"
class="btn mr-2 btn-success"
(click)="evnCreate()"
>
Dodaj wydarzenie
</button>
<button
type="button"
class="btn ml-2 btn-secondary"
(click)="evnAbort()"
>
Anuluj
</button>
</div>
</div>
</div>
</form>
Also, I want to include output from model and response from network monitor:
[Nazwa: "nlnkizcxczx", Opis: "zcxczxzxczxczcx", Ends: "2020-03-04", Ownerusername: "PanMichal"]
Nazwa: "nlnkizcxczx"
Opis: "zcxczxzxczxczcx"
Ends: "2020-03-04"
Ownerusername: "PanMichal"
Network monitor:
As you said, POST body should look like below object:
{
"Nazwa": "String",
"Opis": "Another String",
"Ownerusername": "Another String",
"Ends": "1976-07-28"
}
but you are sending an array
[
Nazwa: "nlnkizcxczx",
Opis: "zcxczxzxczxczcx",
Ends: "2020-03-04",
Ownerusername: "PanMichal"
]
so you should try with sending object instead of an array.
Hope this help
Fixed!
What I did:
I replaced
model: any = [];
To:
model: any = {};
Related
I have built a modal component with 1 textfield and a submit button, with a required validator on that specific textfield. It seems the Validator is working, but somehow the validator error message is not shown.
The typescript code for the component:
#Injectable()
export class AddOrganizationComponent implements OnInit {
public addOrganizationFormGroup: FormGroup;
public submittedAddOrganization = false;
modalService: BsModalService;
formModal: BsModalRef;
form = {
class: "modal-dialog-centered modal-sm"
};
constructor(private addOrganizationFormBuilder: FormBuilder,
private injector: Injector) {
}
ngOnInit(): void {
this.enableAddOrganizationForm();
}
public openAddOrganizationModal() {
this.modalService = this.injector.get(BsModalService);
this.formModal = this.modalService.show(AddOrganizationComponent, this.form);
}
public addOrganization() {
this.submittedAddOrganization = false;
if(this.addOrganizationFormGroup.invalid) {
console.log('Yes is invalid ');
} else {
console.log('Adding Organization function!');
}
}
get addOrganizationFormGroupControls() {
return this.addOrganizationFormGroup.controls;
}
public enableAddOrganizationForm() {
this.addOrganizationFormGroup = this.addOrganizationFormBuilder.group({
organizationName: ['', Validators.required]
});
}
}
The HTML code for the component:
<div class="modal-header text-center">
<div class=" modal-body p-0">
<h6 class=" modal-title" id="modal-title-default">
Add Organization
</h6>
<div class=" card bg-secondary border-0 mb-0">
<div class=" card-header bg-transparent pb-3">
<div class=" text-muted text-center mt-2 mb-3">
<small>Type in the name of your new Organization</small>
</div>
</div>
<div class="card-body">
<form role="form" [formGroup]="addOrganizationFormGroup">
<div class="form-group mb-3">
<div class="input-group input-group-alternative">
<input class="form-control" maxlength="20" placeholder="Enter Organization name" type="text" id="organizationNameText" formControlName="organizationName"
[ngClass]="{ 'is-invalid': submittedAddOrganization && addOrganizationFormGroupControls.organizationName.errors }"/>
<div *ngIf="submittedAddOrganization && addOrganizationFormGroupControls.organizationName.errors" style="color:red;font-size:small">
<div *ngIf="addOrganizationFormGroupControls.organizationName.errors.required">A team name is required</div>
</div>
</div>
<div>
<p class="text-muted" *ngIf="addOrganizationFormGroupControls.organizationName.value">{{addOrganizationFormGroupControls.organizationName.value.length}} / 20</p>
</div>
<br/>
</div>
<div class="text-center">
<button type="button" class="btn btn-primary my-4" (click)="addOrganization()">
Add Organization
</button>
</div>
</form>
</div>
</div>
</div>
</div>
I have searched high and low. It seems the validation is working, but the text is not shown, am I missing something or really looking over something small here?
In method called on button click - addOrganization() - you are setting the submittedAddOrganization to false. However, you are expecting it to be true to display the error. Thus: set it to true in button-click handler method.
I am new to angular, currently I am looking checkboxes in angular , I have three checkboxes and I have to show checked or unchecked checkboxes in UI.
I am getting enabled/disabled from json , I need to show if am getting enabled means checkbox should be checked and disabled means unchecked checkbox.
This is what am trying in html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label for="email"><input type="checkbox" (change)="onChecked($event)" formcontrolName="emailData" value="{{emailData}}" [checked]="isChecked" >
<b>Email(POP3, IMAP, SMTP)</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label for="ftp"><input type="checkbox" formcontrolName="ftpData" [checked]="isChecked" value="{{ftpData}}"> <b>FTP</b></label>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label for="http"><input type="checkbox" formcontrolName="httpData"
[checked]="isChecked"> <b>HTTP</b></label>
</div>
</div>
</form>
typescript file
portFilterForm(){
this.portFilterGroup = this.fb.group({
emailData: new FormControl(''),
ftpData: new FormControl(''),
httpData: new FormControl('')
})
}
onChecked(e){
console.log("e", e.target)
if (e.target == 'enabled'){
this.isChecked = true;
}
else{
this.isChecked = false;
}
}
gettingData(){
this.httpClient.get("assets/json/data.json").subscribe((data:any) =>{
console.log(data);
this.emailData = this.onChecked(data.email)
this.httpData = this.onChecked(data.http)
})
}
and the json file be
{
"email": "enabled",
"ftp": "disabled",
"http": "enabled"
}
this is the code am trying, but am not get the expecting output(enabled means checked and disabled means unchecked) can anyone help me to this?
Ok so you can use the angular way read here
html
<form [formGroup]="portFilterGroup">
<div class="form-group row">
<div class="col-md-4 text-left" id="email">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['emailData']"
/> <b>Email(POP3, IMAP, SMTP)</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="ftp">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>FTP</b></label
>
</div>
</div>
<div class="form-group row">
<div class="col-md-4 text-left" id="http">
<label
><input
type="checkbox"
[formControl]="portFilterGroup.controls['ftpData']"
/> <b>HTTP</b></label
>
</div>
</div>
</form>
{{ portFilterGroup.value | json }}
<button (click)="gettingData()">submit</button>
ts file
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular 6';
portFilterGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.portFilterForm();
}
portFilterForm() {
this.portFilterGroup = this.fb.group({
emailData: new FormControl(false),
ftpData: new FormControl(false),
httpData: new FormControl(false),
});
}
gettingData() {
console.log(this.portFilterGroup.value);
// this.httpClient.get('assets/json/data.json').subscribe((data: any) => {
// console.log(data);
// this.emailData = this.onChecked(data.email);
// this.httpData = this.onChecked(data.http);
// });
}
}
stackblitz
I have this problem:
Property 'institutionName' does not exist on type 'FormGroup'.
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
My ts code
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, AbstractControl, FormGroup, FormControl, FormArray} from '#angular/forms'
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormsComponent implements OnInit {
frmValues: object = {};
frmStepper: FormGroup;
public get formArray(): AbstractControl {
// console.log(this.frmStepper.get('steps'));
return this.frmStepper.get('steps');
}
public get frmStepperControl(){
console.log(this.frmStepper.get('steps')['controls'].controls.institutionName);
return this.frmStepper.get('steps')['controls'];
}
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.frmStepper = this.fb.group({
steps: this.fb.array([
this.fb.group({
ieCode: [''],
institutionName: ['', Validators.compose([Validators.required])],
}),
this.fb.group({
telephone1: [null],
}),
])
});
}
submit(): void {
console.log(this.frmStepper.value.steps[0].institutionName);
//this.frmValues = this.frmStepper.value;
}
}
My html code where I'm trying access the touched and errors properties from my institutionName property
<form [formGroup]="frmStepper" (ngSubmit)="submit()">
<timeline-stepper #cdkStepper formArrayName="steps" [linear]="true">
<cdk-step [editable]="false" formGroupName="0" [stepControl]="formArray.get([0])" class="form-cdk">
<div class="row">
<p>Instituição de ensino</p>
<div class="horizontal-divider"></div>
<div class="form-group col-md-6">
<label for="ieCode">Código da IE/IF</label>
<input formControlName="ieCode" type="text" class="form-control" id="ieCode" placeholder="Escreva aqui...">
</div>
<div class="form-group col-md-6">
<label for="institutionName">Nome da Instituição*</label>
<input formControlName="institutionName" type="text" class="form-control" id="institutionName"
placeholder="Escreva aqui..."
required>
<span class="text-danger"
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
Nome da Instituição é obrigatória
</span>
</div>
</div>
<footer class="row">
<div class="col-md-6"></div>
<div class="form-group col-md-3">
<button type="button" class="btn btn-primary next" cdkStepperNext>PRÓXIMO</button>
</div>
</footer>
</cdk-step>
<cdk-step #contacts [editable]="false" formGroupName="1" [stepControl]="formArray.get([1])">
<div class="row">
<div class="form-group col-md-6">
<label for="telephone1">Telef.1</label>
<input formControlName="telephone1" type="number" class="form-control" id="telephone1" placeholder="Escreva aqui.">
</div>
</div>
<footer class="row lastRow">
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary next">PRÓXIMO</button>
</div>
</footer>
</cdk-step>
</timeline-stepper>
</form>
Property 'institutionName' does not exist on type 'FormGroup'.
I'm facing this problem.
In you HTML you have frmStepper.InstitutionName.errors
Should be frmStepperControl.InstitutionName.errors
Just a quick question here. I'm still a newbie in angular so please. And yes, I have my view page looks something like this.
Initially, i'm loading my page with all the required data. Now, the problem here is, when the user clicks on any of the name in "OWNERS", the data should be able to filter based on "user-click". For example, if the user click on "Krishna" all the campaigns associated with "Krishna" should be filtered and should be able to display in the same page.
My home.component.ts page looks like this.
import { CampaignService } from './../../../services/campaign.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private campaignService : CampaignService ) { }
Time;
campaigns;
ngOnInit(){
setInterval(() => {
this.Time = Date.now()
}, 1000);
this.campaignService.CampaignsInfo()
.subscribe(response=>{
this.campaigns = response;
});
}
}
And my home.component.html looks like this:
<campaign-header></campaign-header>
<div class="container-fluid date-time sticky-top">
<div class="container">
<form class="form-inline my-2 my-lg-0 d-flex justify-content-center radio" >
<div class="" >
<input type="radio" checked name="day"> Today
</div>
<div class="float-left">
<input type="radio" name="day"> Commulative
</div>
<!-- <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>-->
</form>
<div class="d-flex justify-content-end" style="margin-top: -16px;">
<span id="date_time"><i class="zmdi zmdi-calendar-check zmdi-hc-fw"></i> {{Time | date}} <i class="zmdi zmdi-time zmdi-hc-fw"></i> {{ Time | date:'mediumTime' }} </span>
</div>
</div>
</div>
<br>
<!-- content -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="card campaign border-top wrap">
<div class="card-body table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
<th class="border-top-0">CAMPAIGN </th>
<th class="border-top-0">STATUS</th>
<th class="border-top-0">DIALED</th>
<th class="border-top-0">OWNERS</th>
<th class="border-top-0"> <span class="invisible">Action</span></th>
<!-- <button mat-button color="primary" routerLink="/campaign-details">CampaignDetails</button> -->
</tr>
</thead>
<tbody>
<tr *ngFor="let campaign of campaigns?.result">
<td><p>{{campaign.CampaignName}}</p>
<small>{{campaign.DepartmentName}}</small>
</td>
<td>
<small class="text-info">Active</small>
</td>
<td>
<p>{{campaign.Dialed}} / <small>1500000</small></p>
<div class="progress mt-2 w-75">
<div class="progress-bar bg-info" role="progressbar" style="width: 90%;" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</td>
<td>
<button class="badge badge-pill badge-secondary" > {{ campaign.owners }} </button>
</td>
<td class="ml-0 pl-0"><a routerLink="/campaign-details"><img src="../../assets/Images/next.png" class="next" /></a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br>
</div>
I tried writing the (click) ="someMethod(campaign.Name)" for the button and passed campaign object and tried applying filter there in component.ts page, but no luck. Any help is much appreciated. Much thanks in advance.
P.S: This is after some research and after implementing the below suggestion.
I tried implementing a custom pipe, but after click event on owners, i'm getting the following error.
For Information: My debugging value of the pipe after click event looks like this.
My pipe Looks like this.
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(values: any[], key: string, value: string): any[] {
if (!values) {
return [];
}
if (!value) {
return values;
}
return values.filter(val =>{
debugger;
console.log(values);
return val.includes(values);
});
}
}
And my click event and html looks like this:
filterByOwnr(val) {
this.filter = val;
}
<tr *ngFor="let campaign of campaigns?.result | filter : 'OWNERS' : filter;">
<td>
<button class="badge badge-pill badge-secondary" (click)="filterByOwnr(campaign.owner)"> {{ campaign.owner}} </button>
</td>
</tr>
Implement custom filter pipe. Note modify custom pipe as per your need.
import { Pipe, PipeTransform, Injectable } from '#angular/core';
#Pipe({
name: 'filter',
})
#Injectable()
export class Filter implements PipeTransform {
transform(values: any[], key: string, value: string): any[] {
if (!values) {
return [];
}
if (!key|| !value) {
return values;
}
return values.filter(val=>
val[key].toLowerCase().includes(value.toLowerCase())
);
}
}
import { Filter } from 'filterPipe';
#NgModule({
imports: [],
declarations: [ Filter ],
providers: [ ],
exports: [
Filter
],
})
export class PipeModule {}
//App module
import { NgModule } from '#angular/core';
import { PipeModule } from './modules/pipe.module';
#NgModule({
imports: [PipeModule
],
declarations: [
],
providers: [
],
bootstrap: [AppComponent],
})
export class AppModule {}
Home HTML
<tr *ngFor="let campaign of campaigns?.result | filter : 'OWNERS' : searchVal;">
<td class="text-left">
<span (click)="filterByOwnr(campaign.OWNERS)">{{campaign.OWNERS}}</span>
</td>
filterByOwnr(val){
this.searchVal = val;
}
In your custom pipe implementation, shouldn't this line:
return val.includes(values);
Be this instead?
return val.CampaignName.includes(value);
so I have this html code.. i tried using (click) function, and its still like this
<div class="container">
<h1><a [routerLink]="['/databuku']"><img src="images/images.png" width="42" height="42"></a>
Add New Book</h1>
<div class="row">
<div class="col-md-6">
<form (ngSubmit)="saveBuku()" #bukuForm="ngForm">
<div class="form-group">
Judul
<input type="text" class="form-control" [(ngModel)]="buku.judul" name="judul" required>
</div>
<div class="form-group">
Author
<input type="text" class="form-control" [(ngModel)]="buku.author" name="author" required>
</div>
<div class="form-group">
Description
<textarea class="form-control" [(ngModel)]="buku.description" name="description" required cols="40" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" [disabled]="!bukuForm.form.valid">Save</button>
</div>
</form>
</div>
</div>
</div>
here is my ts file
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-tambah-buku',
templateUrl: './tambah-buku.component.html',
styleUrls: ['./tambah-buku.component.css']
})
export class ComponentTambahBuku implements OnInit {
buku = {};
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
}
saveBuku() {
this.http.post('http://localhost:8080/buku', this.buku)
.subscribe(res => {
let id = res['id'];
this.router.navigate(['/detail-buku/', id]);
}, (err) => {
console.log(err);
}
);
}
}
no errors found when I open localhost:4200, its just when i press the save button, its like the button doesn't working, not saving and not going to 'detail-buku' page