我正在尝试使用政府http api(https://github.com/usagov/Corporate-Consumer-Contact-API-Documentation)创建一个使用文本输入搜索公司的搜索功能。
我有一个名为contact-list.component.html的html页面,其上有一个按钮元素,当点击它时,会调用一个存在于组件文件中的函数(contact-list.component.ts)。该函数应该使用传入的字符串来搜索我正在调用的服务来查找公司并将结果输出到我可以绑定到表的数组。
与-list.component.html
<div class='row'>
<div class='col-md-2'>Enter Corporation Name:
</div>
<div class="col-md-4">
<input type="text"
[(ngModel)] = 'searchString'/>
<div><button class='btn btn-primary' ng-click="ContactListComponent.getResults(searchString)">Search</button>
</div>
</div>
</div>
<div class='row'>
与-list.component.ts
getResults(_searchString: string): any{
this._contactService.getContacts(this._searchString)
.subscribe(contacts => this.contacts = contacts,
error => this.errorMessage = <any>error);
}
问题是,当我输入文本并单击按钮时,控制台不显示任何输出,我似乎没有得到任何结果。实际上,当我用
替换getResults()方法中的代码时的console.log(&#34;富&#34);
按下F12时,控制台中没有显示任何内容。关于我缺少的任何想法?
答案 0 :(得分:1)
ng-click
是Angular 1的语法。使用(click)="..."
。
此外,您不需要(且一定不)写"ContactListComponent.getResults(searchString)"
但只需"getResults(searchString)"
,因为您已经在正确的组件中。
此外,您不需要传递searchString
,因为它已在组件this.searchString
中可用。
所以,这里有正确的语法:
(click)="getResults()"
......并在您的组件中:
getResults(): any{
this._contactService
.getContacts(this.searchString) // Already available thanks to [(ngModel)]="searchString"
.subscribe(...);
}
答案 1 :(得分:1)
在朋友的帮助下,我能够解决问题。我的问题不在我之前列出的任何文件中。相反,我在我的应用程序中使用了太多组件区域中的选择器。修复它的原因是我将app.component.ts文件的组件选择器属性更改为app-root,而是从app.component.html调用my。这是一种基本的东西,是我忽略的东西。感谢任何调查我的问题的人。