型号更新,但是角UI不Ngzone甚至重新解析(Model updates but Angular

2019-10-29 05:19发布

我有一个要求,其中从外部输入领域之外角我得到的输入值,使用它我引发了我的角模块服务,从后端获取相关数据。 订阅功能工作正常进行内部的变化,但由于这里的输入值从全局函数来,该UI是没有得到呈现。

我曾尝试zone.rundetectChangedetectCheck但似乎没有被更新UI。 该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>

Answer 1:

请您感兴趣反应上的变化变量适当console.logging添加ngOnChanges()块。 我们可以去那里。 最有可能你会发现:

  • 变量未更新
  • 该变量得到重置为默认状态
  • 另外的变化检测策略是不是设置为你希望

您将需要挂钩添加到您的类定义OnChanges正常闪光:

export class SearchSuggestionComponent implements OnInit, OnChanges {

更新:我添加代码到plunkr和嘲笑你的服务电话。 看来你可能有更好的运气,如果您移动填充suggestedItems到您的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的对象,以确保角是蓄势待发,模板实现了时间绑定到组件的代码,改变检测操作。 很多时候完成工作之前ngOnInit会导致模板问题的角度不完全剥离了没有。

希望这可以帮助! 干杯



文章来源: Model updates but Angular Ui does not Rerender even with Ngzone
标签: angular