I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value is sent, it should return all possible values.
The main problem arises when I submit the form. I am faced with errors such as:
- Cannot read property 'value' of undefined;
- _this.form.get is not a function.
Below is the code snippet:
Service
@Injectable()
export class FleetService {
private defUrl = 'some.url';
constructor(private http: Http) { }
getFleet(fleetname?: string) {
const url = (!fleetname) ? this.defUrl : 'some.url=' + fleetname;
return this.http.get(url)
.map(res => res.json());
}
}
Component
export class FleetComponent implements OnInit {
ngOnInit() {
this.searchQuery = new FormGroup({
fleetname: new FormControl('', Validators.required)
});
}
public flota: FleetHead[];
public searchQuery: FormGroup;
constructor(private fleetService: FleetService, private router: Router) {
this.fleetService.getFleet().subscribe(fleet => {
this.flota = fleet;
})
}
search(searchQuery) {
this.fleetService
.getFleet(searchQuery.value.fleetname)
.subscribe(searchQuery => {
this.searchQuery = searchQuery;
this.router.navigate(['/fleet']);
})
}
}
interface FleetHead {
fleets: FleetInfo[];
}
interface FleetInfo {
id: number;
name: string;
}
Template
<form class="form-inline" novalidate (ngSubmit)="search(fleetname)" [formGroup]="searchQuery">
<div class="form-group">
<input class="form-control" formControlName="fleetname" type="text" placeholder="Search">
</div>
<button class="btn btn-info" type="submit">Search</button>
</form>
<div *ngIf="flota">
<p-dataTable [value]="flota.fleets">
<p-header>Search results</p-header>
<p-column field="id" header="ID" [sortable]="true"></p-column>
<p-column field="name" header="Name" [sortable]="true"></p-column>
</p-dataTable>
</div>
While using this template, I encountered the error
Cannot read property 'value' of undefined
. When I added #fleetname
to the input, it resulted in _this.form.get is not a function
.
This template operates on route /fleet
, and upon submission, I aim to remain on the page with updated values for potentially different search results.