Блок NgIf в Angular breaks Http Call - PullRequest
       1

Блок NgIf в Angular breaks Http Call

0 голосов
/ 18 октября 2018

Без блока 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);
  }

ОШИБКА TypeError: Невозможно прочитать свойство 'next' из неопределенного в SafeSubscriber._next (service-now.component.ts: 124) в SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub (Subscriber.js: 196) в

Ответы [ 2 ]

0 голосов
/ 18 октября 2018

Вам необходимо объявить и инициализировать каждую переменную в файле .ts, который динамически заполняется.

В вашем коде вы напрямую пытаетесь присвоить значение неопределенной переменной. Поэтому убедитесь, что вы определили или присвоили какое-то значениек этому.

taskObserver = new Subject<any>(); //import { Subject } from 'rxjs';

здесь вы идете ... хороший справочный сайт для объяснения

0 голосов
/ 18 октября 2018

Похоже, вы не инициализировали свою переменную taskObserver

Убедитесь, что вы инициализировали как -

taskObserver = new Subject<any>();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...