【问题标题】:NgIf block in Angular breaks Http CallAngular 中的 NgIf 块中断了 Http 调用
【发布时间】:2018-10-18 02:07:59
【问题描述】:

没有 ngIf 块,http 调用可以正常工作,并且表格被填充而没有任何问题,但是使用 ngIf 块,我得到的错误是

<div *ngIf="isloading; else other_content">
      <ng-template #content>
        <mat-progress-spinner [color]="color"
                              [mode]="mode"
                              [value]="value">
        </mat-progress-spinner>
      </ng-template>
    </div>
    <ng-template #other_content>
      <uitk-dynamic-table id="incidentTable" #dt [model]="incidents" [modelObservable]="incidentObservable">
        <uitk-column-def [id]="incidents.columns[0].id">
          <ng-template #cellTemplate let-col="column" let-record="record">
            <span>{{record[col.id]}}</span>
          </ng-template>
        </uitk-column-def>
      </uitk-dynamic-table>
      <h2>Tasks</h2>
      <uitk-dynamic-table id="taskTable" #dt [model]="tasks" [modelObservable]="taskObservable">
        <uitk-column-def [id]="tasks.columns[0].id">
          <ng-template #cellTemplate let-col="column" let-record="record">
            <span>{{record[col.id]}}</span>
          </ng-template>
        </uitk-column-def>
      </uitk-dynamic-table>
    </ng-template>

这是组件代码

    private incidentObservable: Observable<any>;
  private incidentObserver: Observer<any>;
  private taskObservable: Observable<any>;
  private taskObserver: Observer<any>;
  private employeeID: string;
  private msID: string;
  private incidentAPI: string;
  private incidentID: string;
  private taskAPI: string;
  private id: string;
  private isloading: boolean;

  color = 'primary';
  mode = 'indeterminate';
  value = 50;

  incidents = {
    title: 'Incidents',
    enableSorting: true,
    enableFiltering: false,
    clearAllFilters: false,
    caseSensitiveFilter: true,
    fixedHeader: true,
    filterCondition: {
      columnSorting: {
        columnId: 'IncidentId',
        sortOrder: 1
      }
    },
    columns: [
      { label: 'Incident', id: 'IncidentId', dataType: 'text' },
      { label: 'Description', id: 'ShortDescription', dataType: 'text' },
      { label: 'Assignment', id: 'Assignment', dataType: 'text' },
      { label: 'State', id: 'State', dataType: 'text' },
      { label: 'UksProduct', id: 'UksProduct', dataType: 'text' },
      { label: 'Owner', id: 'WorkgroupOwner', dataType: 'text' },
      { label: 'Opened', id: 'DateOpened', dataType: 'date' },
      { label: 'SLA', id: 'SlaIndicator', dataType: 'text' },
      { label: 'Caller', id: 'SlaIndicator', dataType: 'text' },
      { label: 'Closed', id: 'SlaIndicator', dataType: 'date' }
    ],
    records: []
  };


  tasks = {
    title: 'Tasks',
    enableSorting: true,
    enableFiltering: false,
    clearAllFilters: false,
    caseSensitiveFilter: true,
    fixedHeader: true,
    filterCondition: {
      columnSorting: {
        columnId: 'TaskId',
        sortOrder: 1
      }
    },
    columns: [
      { label: 'Task', id: 'TaskId', dataType: 'text' },
      { label: 'Description', id: 'ShortDescription', dataType: 'text' },
      { label: 'Assignment', id: 'Assignment', dataType: 'text' },
      { label: 'State', id: 'State', dataType: 'text' },
      { label: 'Opened', id: 'CreateDate', dataType: 'date' },
      { label: 'Caller', id: 'SlaIndicator', dataType: 'text' },
      { label: 'Closed', id: 'SlaIndicator', dataType: 'date' }
    ],
    records: []
  };

  tempModel = {
    subText: "The application will be available shortly."
    //imageUrl: "../../loading.png" // Test to display under the Page Loader
  };

  constructor(private _http: HttpClient, private _cardService: DashboardCardService, private plis: PageLoadingIndicatorService) {
    this.incidentObservable = new Observable(obj => this.incidentObserver = obj);
    this.taskObservable = new Observable(obj => this.taskObserver = obj);
  }

  ngOnInit() {

    this.plis.showLoader();
    this.isloading = true;

    this._cardService.InputData.subscribe(data => {
      this.employeeID = data.EmployeeId;
      this.msID = data.MSId;
      this.incidentID = data.MSId;
    });
    // if employeeID is null, then msid would be used to fetch the data. employeeID is given preference over msid as it will be more accurate. If required, we can change the order later
    this.id = this.employeeID || this.msID || this.incidentID;

    this.getIncidentData().subscribe((incidentResponse) => {
      setTimeout(() => {
        this.isloading = false;
        console.log(incidentResponse);
        this.incidents.records = incidentResponse.Incidents.slice(0, 5);
        this.incidentObserver.next(this.incidents);

      }, 8000);

    });

    this.getTaskData().subscribe((taskResponse) => {
      console.log(taskResponse);
      this.tasks.records = taskResponse.Tasks.slice(0, 5);
      this.taskObserver.next(this.tasks);

    });
  }

  getIncidentData(): Observable<any> {
    //If you are running just the angular App alone instead of running the entire application, uncomment the below line and comment the service call
    //return this._http.get('incident.json');
    this.incidentAPI = AppConstants.incidentAPI + this.id;
    return this._cardService.getIncidentData(this.incidentAPI);
  }

  getTaskData(): Observable<any> {
    //If you are running just the angular App alone instead of running the entire application, uncomment the below line and comment the service call
    // return this._http.get('task.json');
    this.taskAPI = AppConstants.taskAPI + this.id;
    return this._cardService.getTaskData(this.taskAPI);
  }

ERROR TypeError: Cannot read property 'next' of undefined 在 SafeSubscriber._next (service-now.component.ts:124) 在 SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196) 在

【问题讨论】:

  • 请在代码中提供更多上下文。 this.getTaskData() 在哪里调用?
  • 它在相应的组件文件中被调用..正如我所提到的,如果我不使用 if else 块而只使用 table 指令,它工作正常

标签: angular angular5


【解决方案1】:

您需要在动态填充的 .ts 文件中声明和初始化每个变量。

在您的代码中,您直接尝试将值分配给未定义的变量。因此请确保为此定义或分配一些值。

taskObserver = new Subject&lt;any&gt;(); //import { Subject } from 'rxjs';

here you go...good ref site for explanantion

【讨论】:

  • 我还没有粘贴整个组件代码,但是声明已经被注意了。正如我所说,它可以在没有 ngif 块的情况下工作
  • 我不知道根本原因。但是如果我为表
    隐藏可见性,而不是像 它那样工作..不知道是什么情况
  • 你能试试[ngIf]="isloading" [ngIfElse]="otherContent"把这个条件放在&lt;ng-template #content&gt;这个block.remove外部&lt;div&gt;block.并确保使用camel case而不是_(undescore)
  • 谢谢。我会尝试这种方式并更新您。同时,我对您为 BehaviourSubject 共享的链接提出了一个问题。我之前也将它发布在stackoverflow中。为了在组件之间共享数据,具有私有范围变量的普通服务就可以了。对.. 为什么我们需要专门针对 BehaviourSubject?
  • @NewBee,根据我的理解,A BehaviorSubject 拥有一个值。当它被订阅时,它会立即发出值。主题不包含值。假设你用Subject 创建了一个对象,然后你调用.next(1) ,那么你的输出将为空,但如果你对BehaviourSubject 做同样的事情,你会得到输出为1。
【解决方案2】:

看起来你没有初始化你的变量taskObserver

确保你已经初始化为 -

taskObserver = new Subject<any>();

【讨论】:

  • 我声明了它,只是为了发帖,我分享了一半的代码。正如我在帖子中提到的那样,如果我删除 html 中的 ngif 模板并单独包含 table 指令,代码就可以工作
  • 你能在this.incidentObserver调用next函数之前打印它的日志吗?
  • 我进行了调试,当它到达 this.incidentObserver 时,它是未定义的。正如你所看到的,我在顶部删除了它,如果我删除我的 ngIF 模板并调试代码,它工作正常
  • 我不知道根本原因。但是,如果我为表
    隐藏可见性而不是像 那样做它可以工作..不知道是什么情况
猜你喜欢
相关资源
最近更新 更多
热门标签