【问题标题】:ANgular2 auto suggestion server call going in infinite loopAngular2自动建议服务器调用无限循环
【发布时间】:2017-07-17 07:36:37
【问题描述】:

尝试使用 Angular js 实现自动建议

 $ npm install ng2-auto-complete --save

将地图和包添加到systemjs.config.js

 map['ng2-auto-complete'] = 'node_modules/ng2-auto-complete/dist';
 packages['ng2-auto-complete'] = { main: 'ng2-auto-complete.umd.js', ...]

添加组件

 @Component({
    selector: 'person',
    templateUrl: 'app/person/person.component.html'
})
personalData(personName: String): Observable<DepartmentModel[]>{
        let headers = new Headers();        
            if(personName!= undefined){

                headers.append('Content-Type','application/json');
                headers.append('Access-Control-Allow-Origin', '*');
             return this.http.post(AppUtils.GET__MASTER_URL //return a list of department
             ,{personName:personName}
             ,{headers:headers})
                            .map(response => response.json())
                            .catch(this.handleError);
            }


    }

在 person.component.html 添加标签

<input auto-complete [(ngModel)]="myData"  [source]="personalData('test')" />

它在循环调用服务..浏览器被挂了。

用过这个:https://github.com/ng2-ui/auto-complete

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    绑定到类似的方法

    [source]="personalData('test')"
    

    导致变更检测在每个变更检测周期调用personalData('test')

    解决此问题的常用方法是将personalData('test') 的结果分配给一个属性,然后绑定到该属性。

    ngOnInit() {
      this.personalData('test').subscribe(val => this.pd = val);
    }
    

    然后使用

    [source]="pd"
    

    【讨论】:

    • 每次按键/向上时,我都必须从服务中获取数据。所以我最初无法加载所有值。
    • 您可以使用事件绑定(keypress)="personalData('test')" 来调用该方法,但不要在属性绑定中使用它。事件发生时执行事件绑定,每次运行更改检测时执行属性绑定。
    • 为什么没有显示自动建议列表?任何帮助
    • 对不起,我不知道ng2-auto-complete
    • 在 angular2 中是否实现了另一个自动完成功能?
    【解决方案2】:

    根据文档

    source, array or string, required. data source for dropdown list
    

    您正在使用一种方法来填充源personalData('test')

    因此对于每个 DOM 更新服务调用都会进行。

    【讨论】:

    • 如何完成?我需要从数据库中获取列表
    【解决方案3】:

    您可以在(ngModelChange)="search1($event)" 上触发服务调用并调用该服务并获取数据并将其绑定到[source]="data",其中data 包含从上次搜索中接收到的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-26
      • 2019-12-23
      • 2021-02-28
      • 2013-02-02
      • 2012-03-20
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多