错误:
EXCEPTION:未捕获(在承诺中):错误:app / search / search.component.html:10:35导致错误:无法读取未定义的属性'searchFor'
我有这个html文件,我需要创建一个名为'chemical'的对象,它将具有两个属性:1)searchFor(来自文本输入)2)searchBy(来自下拉菜单),如下所示:
<div class="container">
<div class="row">
<div class="col-sm-12 bevisible">
<h3>Search for chemical entries</h3>
</div>
</div>
<form>
<div class="form-group row">
<label for="searchFor" class="col-sm-2 col-form-label">Search For</label>
<div class="col-sm-10">
<input type="text" [(ngModel)]="chemical.searchFor"
name="searchbox"
class="form-control" id="searchFor"
placeholder="Search an Entry...">
</div>
</div>
<div class="form-group row">
<label for="searchType" class="col-sm-2 col-form-label">Search by</label>
<div class="col-sm-10">
<select class="custom-select" id="searchType" [(ngModel)]="chemical.searchBy" name="searchdropdown">
<option selected>Search type</option>
<option value="1">Reagent Barcode</option>
<option value="2">Catalog#</option>
<option value="3">Bottle Label</option>
<option value="3">Location Barcode</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button type="submit" (click)="getChemicalEntries(chemical)" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
创建化学对象后,我想将其传递给组件端定义的getChemicalEntries(chemical)
函数。
这是相关的组件:
import {Component, Input} from '@angular/core';
import {SearchService} from '../services/searchservice.component';
import {Chemical} from "../chemical";
@Component({
selector: 'bioshoppe-search',
providers:[SearchService],
templateUrl: 'app/search/search.component.html',
styleUrls: ['../../css/search.component.css', '../../css/style.css']
})
export class SearchComponent {
@Input () chemical : Chemical;
public chemicals;
public error;
constructor(private searchService: SearchService) {
};
// ngOnInit() {
// this.getChemicals();
// }
getChemicals() {
this.searchService
.getChemicalEntries()
.subscribe(
// the first argument is a function which runs on success
data => {
this.chemicals = data
},
// the second argument is a function which runs on error
err => {
console.error(err), this.error = true
},
// the third argument is a function which runs on completion
() => console.log("done loading chemicals")
);
}
}
PS:我是Angular2的新手。有Angular 1.4的经验。
答案 0 :(得分:0)
这实际上是一个简单的JavaScript错误。您正尝试从模板访问searchFor
对象的chemical
属性。但是,当模板首次尝试访问其属性时,chemical
对象未定义,这就是您收到错误的原因。要解决这个问题,您只需要将一个空的或默认的对象分配给化学品&#39;。例如:
@Input() chemical: Chemical = {
searchFor: '',
searchBy: ''
};
波纹管也可以正常工作,但上面的是TypeScript的最佳实践。
@Input() chemical: any = {}