模型更新,但Angular Ui即使使用Ngzone也不会重新渲染

时间:2018-02-25 13:03:37

标签: angular

我有一个要求,从Angular外部的外部输入字段我得到输入值,使用它我在Angular模块中触发服务从后端获取相关数据。订阅功能适用于内部更改但由于输入值来自全局函数,因此UI不会被渲染。

我尝试了zone.rundetectChangedetectCheck,但似乎没有更新用户界面。 UI应该使用suggestedItems数组显示项目列表。请让我知道什么是错的。

    import { Component, OnInit, HostListener, NgZone, ChangeDetectorRef } from '@angular/core';
    import { BackendApiService } from '../services/backend-api.service';
    import { WindowAccessService } from '../services/window-access.service';
    @Component({
      selector: 'app-search-suggestion',
      templateUrl: './search-suggestion.component.html',
      styleUrls: ['./search-suggestion.component.scss']
    })
    export class SearchSuggestionComponent implements OnInit {
      suggestionHeaders = ['Item', 'Item name', 'Item category', 'Item details'];
      suggestedItems; dummyRequestObj; value;

      calledFromOutside(newValue: String) {
        this.zone.run(() => {
        this.value = newValue;
        this.dummyRequestObj.conditions = [];
        this.dummyRequestObj.conditions.push({
                        'column': 'SEARCH_BY_NAME',
                        'value': this.value
                        });
          // this.chngDt.detectChanges();
        this.items.getData(this.dummyRequestObj, false, false);
        console.log(this.value);
      });
      }
      // tslint:disable-next-line:max-line-length
      constructor( public items: BackendApiService, private zone: NgZone, public refWin: WindowAccessService, private chngDt: ChangeDetectorRef) {
        this.suggestedItems = new Array<any>();
    }
    ngOnInit() {
        this.items.updateItemList.subscribe(
          (data) => {
            console.log('was triggered');
            this.zone.run(() => {
            this.suggestedItems = data;
            });
            // this.chngDt.markForCheck();
            console.log('data', this.suggestedItems);
          }
        );
        this.refWin.nativeWindow.angularComponentRef = {
          zone: this.zone,
          componentFn: (value) => this.calledFromOutside(value),
          component: this
        };
        this.dummyRequestObj = {
                    "preciseSearch": false,
                    "useFuzzy": false,
                    "mode": 0,
                    "startIndex": 0,
                    "noOfRecords": 12,
                    "ascending": false
    };
    }
<div class="table-responsive">
    <table class="table table-hover">
        <thead>
            <tr>
                <th  *ngFor="let header of suggestionHeaders">{{header}</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of suggestedItems">
                <td>{{item.erpPartNumber}}</td>
                <td>{{item.itemShortDesc}}</td>
                <td>{{item.productCategoryName}}</td>
                <td>{{item.itemDesc}}</td>
           </tr>
        </tbody>
    </table>
</div>

1 个答案:

答案 0 :(得分:0)

请为您感兴趣的变量添加一个ngOnChanges()块和相应的console.logging。我们可以去那里。很可能你会发现:

  • 变量未更新
  • 变量将重置为默认状态
  • 或者,更改检测策略未按预期设置

您需要在OnChanges的类定义中添加钩子才能正确触发:

export class SearchSuggestionComponent implements OnInit, OnChanges {

更新:我将您的代码添加到了一个plunkr并嘲笑了您的服务电话。如果您将填充suggestItems的代码移动到ngOnInit中,似乎您可能会有更好的运气:

import { Component, OnInit, NgZone, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
        <tr>
          <th *ngFor="let header of suggestionHeaders">{{header}}</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let item of suggestedItems">
          <td>{{item.erpPartNumber}}</td>
          <td>{{item.itemShortDesc}}</td>
          <td>{{item.productCategoryName}}</td>
          <td>{{item.itemDesc}}</td>
        </tr>
        </tbody>
      </table>
    </div>`
})
export class AppComponent implements OnInit {
  suggestionHeaders = ['Item', 'Item name', 'Item category', 'Item details'];
  suggestedItems; dummyRequestObj; dummyResponseObj; value; items;

  // tslint:disable-next-line:max-line-length
  constructor( ) {
    this.suggestedItems = new Array<any>();
  }
  ngOnInit() {
    this.dummyResponseObj =  [ {'erpPartNumber': 'dadd', 'itemShortDesc': 'Mobile', 'itemDesc': 'LG Mobile',
      'productCategoryCode': '42', 'productCategoryName': 'Prisoners defense services', 'uom': 'EA'},
      {'erpPartNumber': 'data 2', 'itemShortDesc': 'Mobile', 'itemDesc': 'LG Mobile',
        'productCategoryCode': '323', 'productCategoryName': 'Prisoners defense services', 'uom': 'EA'}];

    this.items = this.dummyResponseObj;
    this.suggestedItems = this.dummyResponseObj;
         }
}

基本上你是想尽快补充这个变量。您需要更新OnInit中的对象以确保Angular准备就绪,模板会及时绑定到组件代码,并且更改检测是可操作的。很多时候在ngOnInit之前完成的工作会导致模板问题,因为Angular尚未完全旋转。

希望这有帮助! 欢呼声