每次按下时按钮都不会为组件充电

时间:2017-07-29 21:01:03

标签: javascript html angular

我的主要组件中有按钮的形式,我有两个组件,但第一个是默认数据(在范围时间内,init,结束日期和obra,st,folio,专业是字符串),当我按下我的时候按钮我用这些数据调用我的组件,但是当我再次按下按钮时,我的组件没有再次调用。

我从浏览器添加图片来解释我的问题。

Browser console image

正如你可以看到line [data-table,constructor]正在调用默认值(last day),在第二种情况下我改变了init和end,但是当我再次尝试不用我的显示我的[data-table,constructor]时数据,因为我没有调用组件,任何想法为什么?

这是我的dashboard.component.html,我在其中调用组件来呈现数据。

<app-data-table *ngIf=!active [start]=defaultDateStart [end]=defaultDateEnd>
          Loading data-table...
        </app-data-table>
        <app-data-table
          *ngIf=active
          [start]=defaultDateStart
          [end]=defaultDateEnd
          [obra]=selectedObra
          [st]=selectedST
          [folio]=selectedFolio
          [profesional]=selectedProfesional>
          Loading data-table...
</app-data-table>

这是我的onSubmit(f),当我在表单中按下按钮时会调用此函数。

onSubmit(f: NgForm) {
    if (f.value["init"] == null || f.value["init"] == "") {
      alert("Ingrese la fecha de inicio.");
      return;
    }
    if (f.value["end"] == null || f.value["end"] == "") {
      alert("Ingrese la fecha final.");
      return;
    }
    if (f.value["init"] > f.value["end"]) {
      alert("Las fechas no tienen coherencia.")
      return;
    }
    if (f.value["obra"] == null) {
      console.log("Obra no seleccionada");
    }
    if (f.value["st"] == null) {
      console.log("ST no seleccionada");
    }
    if (f.value["folio"] == null) {
      console.log("Folio no seleccionado");
    }
    if (f.value["profesional"] == null) {
      console.log("Profesional no seleccionado");
    }
    this.defaultDateStart = this.localISOTime(f.value["init"]);
    this.defaultDateEnd = this.localISOTime(f.value["end"]);
    this.active = true;
    console.log("Form values -> ", f.value);
}

更新

我添加了dashboard.component.html

<div layout="row" layout-margin layout-wrap layout-align="center center">
  <md-card flex="100" class="md-card-dashboard">
    <md-card-title>BUSCADOR DE IMÁGENES
    </md-card-title>
    <md-card-subtitle>FILTROS</md-card-subtitle >
    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <md-card>
        <div
          class="container"
          fxLayout
          fxLayout.xs="column"
          fxLayoutAlign="center"
          fxLayoutGap="10px"
          fxLayoutGap.xs="0">
          <div class="item item-1" fxFlex="90%" fxFlexOrder="1">
            <div
              class="container"
              fxLayout
              fxLayout.xs="row"
              fxLayoutAlign="center"
              fxLayoutGap="10px"
              fxLayoutGap.xs="0">
              <div class="item item-1" fxFlex="20%" fxFlexOrder="1">
                <md-input-container>
                  <input
                    mdInput
                    [mdDatepicker]="pickerInit"
                    placeholder="Fecha inicial"
                    [min]="minDate"
                    [max]="maxDate"
                    [value]="10-2-2017"
                    name="init"
                    #init="ngModel"
                    ngModel
                    required>
                  <button mdSuffix [mdDatepickerToggle]="pickerInit"></button>
                </md-input-container>
                <md-datepicker #pickerInit></md-datepicker>
              </div>
              <div class="item item-2" fxFlex="23%" fxFlexOrder="2">
                <md-input-container>
                  <input
                    mdInput
                    [mdDatepicker]="pickerEnd"
                    placeholder="Fecha final"
                    [min]="minDate"
                    [max]="maxDate"
                    name="end"
                    ngModel
                    required>
                  <button mdSuffix [mdDatepickerToggle]="pickerEnd"></button>
                </md-input-container>
                <md-datepicker #pickerEnd></md-datepicker>
              </div>
              <div class="item item-3" fxFlex="62%" fxFlexOrder="3">
                <div
                  class="container"
                  fxLayout
                  fxLayout.xs="row"
                  fxLayoutAlign="center"
                  fxLayoutGap="20px"
                  fxLayoutGap.xs="0">
                  <div class="item item-1" fxFlex="20%" fxFlexOrder="1">
                    <md-select placeholder="Obra" [(ngModel)]="selectedObra" name="obra">
                      <md-option *ngFor="let obra of obras" [value]="obra.value">
                        {{obra.value}}
                      </md-option>
                    </md-select>
                    <p>
                      {{selectedObra}}
                    </p>
                  </div>
                  <div class="item item-2" fxFlex="30%" fxFlexOrder="2">
                    <md-select placeholder="ST" [(ngModel)]="selectedST" name="st">
                      <md-option *ngFor="let st of sts" [value]="st.value">
                        {{st.value}}
                      </md-option>
                    </md-select>
                    <p>
                      {{selectedST}}
                    </p>
                  </div>
                  <div class="item item-3" fxFlex="30%" fxFlexOrder="3">
                    <md-select placeholder="Folio" [(ngModel)]="selectedFolio" name="folio">
                      <md-option *ngFor="let folio of folios" [value]="folio.value">
                        {{folio.value}}
                      </md-option>
                    </md-select>
                    <p>
                      {{selectedFolio}}
                    </p>
                  </div>
                  <div class="item item-4" fxFlex="30%" fxFlexOrder="4">
                    <md-select
                      placeholder="Profesional"
                      [(ngModel)]="selectedProfesional"
                      name="profesional">
                      <md-option
                        *ngFor="let profesional of profesionales"
                        [value]="profesional.value">
                        {{profesional.value}}
                      </md-option>
                    </md-select>
                    <p>
                      {{selectedProfesional}}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="item item-2" fxFlex="10%" fxFlexOrder="2">
            <button md-raised-button>Buscar</button>
          </div>
        </div>
      </md-card>
    </form>

    <md-card-content>
      <md-card style="background-color:rgba(176,224,230,0.2);">
        <md-card-title>RESULTADOS</md-card-title>
        <app-data-table *ngIf=!active [start]=defaultDateStart [end]=defaultDateEnd>
          Loading data-table...
        </app-data-table>
        <app-data-table
          *ngIf=active
          [start]=defaultDateStart
          [end]=defaultDateEnd
          [obra]=selectedObra
          [st]=selectedST
          [folio]=selectedFolio
          [profesional]=selectedProfesional>
          Loading data-table...
        </app-data-table>
      </md-card>
    </md-card-content>
    <md-card-footer style="text-align:center">© 2017</md-card-footer>
  </md-card>
</div>

我的dashboard.component.ts带有新功能(我正在尝试解决此问题)reloadWithNewId()

import { Component, OnInit, Input } from '@angular/core';
import { NgForm, NgModel } from '@angular/forms';
import { DateAdapter } from '@angular/material';
import {MdSelectChange} from '@angular/material';
import {SelectionService} from '../shared/selection.service';
import {SelectionData} from '../shared/selection-data';
import {ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  active: boolean;
  start: string;
  end: string;
  defaultDateStart: Date;
  defaultDateEnd: Date;
  minDate = new Date(2000, 0, 1);
  maxDate = new Date(Date.now());
  selectionData: SelectionData;
  obras: string[];
  sts: string[];
  folios: string[];
  profesionales: string[];

  constructor(
    private dateAdapter: DateAdapter<Date>,
    private selectionService: SelectionService,
    private route: ActivatedRoute,
    private r: Router) {
    dateAdapter.setLocale('nl'); //DD-MM-YYYY
    this.active = false;
  }

  ngOnInit() {
    let date = new Date(Date.now());
    let date_end = date;
    this.defaultDateEnd = date_end;
    this.defaultDateStart = new Date(date);
    this.defaultDateStart.setDate(this.defaultDateStart.getDate() - 1);
    this.defaultDateStart = this.localISOTime(this.defaultDateStart);
    this.defaultDateEnd = this.localISOTime(this.defaultDateEnd);
    console.log("init ", this.defaultDateStart);
    console.log("end ", this.defaultDateEnd);
    this.getDataFilters();
  }

  localISOTime(d): any {
    if (!d)
      d = new Date()
    var tzoffset = d.getTimezoneOffset() * 60000; //offset in milliseconds
    return (new Date(d - tzoffset)).toISOString().slice(0, -1);
  }

  setData(array: string[]): any[] {
    let objetos = new Array<any>();
    for (var ix of array) {
      objetos.push({ value: ix });
    }
    return objetos;
  }
  getDataFilters(): void {
    this.selectionService.getData().then(data => {
      this.selectionData = data;
      this.obras = this.setData(this.selectionData[2]["obra"]);
      this.sts = this.setData(this.selectionData[0]["st"]);
      this.folios = this.setData(this.selectionData[1]["folio"]);
      this.profesionales = this.setData(this.selectionData[3]["profesional"]);
    });

  }
  selectedObra: string;
  selectedST: string;
  selectedFolio: string;
  selectedProfesional: string;

  reloadWithNewId() {
    console.log("reloadWithNewId");
    this.r.navigateByUrl('/home');
  }

  onSubmit(f: NgForm) {
    if (!f.value["init"]) {
      alert("Ingrese la fecha de inicio.");
      return;
    }
    if (!f.value["end"]) {
      alert("Ingrese la fecha final.");
      return;
    }
    if (f.value["init"] > f.value["end"]) {
      alert("Las fechas no tienen coherencia.")
      return;
    }
    if (f.value["obra"] == null) {
      console.log("Obra no seleccionada");
    }
    if (f.value["st"] == null) {
      console.log("ST no seleccionada");
    }
    if (f.value["folio"] == null) {
      console.log("Folio no seleccionado");
    }
    if (f.value["profesional"] == null) {
      console.log("Profesional no seleccionado");
    }
    this.defaultDateStart = this.localISOTime(f.value["init"]);
    this.defaultDateEnd = this.localISOTime(f.value["end"]);
    this.active = true;
    console.log("Form values -> ", f.value);
    this.reloadWithNewId();
  }
}

NEW UPDATE

我添加了我的data-table.component.ts和我的data-table.service.ts

import {Component, ElementRef, ViewChild, Input, OnInit} from '@angular/core';
import {DataSource} from '@angular/cdk/table';
import {MdPaginator, MdSort, SelectionModel} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/debounceTime';

import { DataTableService } from '../shared/data-table.service';
import { DataTable } from '../shared/data-table';
import { Router }   from '@angular/router';


/**
 * @title Feature-rich data table
 */
@Component({
  selector: 'app-data-table',
  styleUrls: ['data-table.component.css'],
  templateUrl: 'data-table.component.html',
})
export class DataTableComponent {
  displayedColumns = ['select', 'foto', 'obra', 'st', 'folio', 'profesional', 'date'];
  exampleDatabase: ExampleDatabase | null;
  selection = new SelectionModel<string>(true, []);
  dataSource: ExampleDataSource | null;
  photos: DataTable[];
  @Input() start: string;
  @Input() end: string;
  @Input() obra: string;
  @Input() st: string;
  @Input() folio: string;
  @Input() profesional: string;
  @ViewChild(MdPaginator) paginator: MdPaginator;
  @ViewChild(MdSort) sort: MdSort;
  @ViewChild('filter') filter: ElementRef;

  constructor(
    private router: Router,
    private datatableService: DataTableService) {
  }

  ngOnInit() {
    this.exampleDatabase = new ExampleDatabase(this.datatableService, this.start, this.end, this.obra, this.st, this.folio, this.profesional);
    //this.getDataTable(this.start, this.end);
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.paginator, this.sort);
    console.log("[data-table, ngOnInit] ");

  }

  gotoDetail(foto: string): void {
    this.router.navigate(['/detail', foto]);
  }

  isAllSelected(): boolean {
    if (!this.dataSource) { return false; }
    if (this.selection.isEmpty()) { return false; }

    if (this.filter.nativeElement.value) {
      return this.selection.selected.length == this.dataSource.renderedData.length;
    } else {
      return this.selection.selected.length == this.exampleDatabase.data.length;
    }
  }

  masterToggle() {
    if (!this.dataSource) { return; }

    if (this.isAllSelected()) {
      this.selection.clear();
    } else if (this.filter.nativeElement.value) {
      this.dataSource.renderedData.forEach(data => this.selection.select(data.id));
    } else {
      this.exampleDatabase.data.forEach(data => this.selection.select(data.id));
    }
  }
}


/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase implements OnInit {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<DataTable[]> = new BehaviorSubject<DataTable[]>([]);
  get data(): DataTable[] { return this.dataChange.value; }
  photos: DataTable[];
  s: string;
  e: string;
  o: string;
  st: string;
  f: string;
  p: string;
  ngOnInit() {
    console.log("ngOnInit ExampleDatabase");
    if (!this.o)
      this.o = "";
    if (!this.st)
      this.st = "";
    if (!this.f)
      this.f = "";
    if (!this.p)
      this.p = "";
    this.getDataTable(this.s, this.e, this.o, this.st, this.f, this.p);
  }
  constructor(private datatableService: DataTableService, start: string, end: string, obra: string, st: string, folio: string, profesional: string) {
    this.s = start;
    this.e = end;
    this.o = obra;
    this.st = st;
    this.f = folio;
    this.p = profesional;
    console.log("[data-table, constructor] ", this.s, this.e, this.o, this.st, this.f, this.p);
    this.ngOnInit();
  }

  //getDataTable call dataTableService with two dates
  getDataTable(start: string, end: string, obra: string, st: string, folio: string, profesional: string): void {
    this.datatableService.getData(start, end, obra, st, folio, profesional).then(photos => {
      //this.dataChange = photos;
      for (let i = 0; i < photos.length; i++) {
        const copiedData = this.data.slice();
        photos[i].id = (i + 1).toString();
        copiedData.push(photos[i]);
        this.dataChange.next(copiedData);
      }
    })

  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  _filterChange = new BehaviorSubject('');
  get filter(): string { return this._filterChange.value; }
  set filter(filter: string) { this._filterChange.next(filter); }


  filteredData: DataTable[] = [];
  renderedData: DataTable[] = [];

  constructor(private _exampleDatabase: ExampleDatabase,
    private _paginator: MdPaginator,
    private _sort: MdSort) {
    super();
    // Reset to the first page when the user changes the filter.
    this._filterChange.subscribe(() => this._paginator.pageIndex = 0);
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<DataTable[]> {
    // Listen for any changes in the base data, sorting, filtering, or pagination
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.mdSortChange,
      this._filterChange,
      this._paginator.page,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      // Filter data
      this.filteredData = this._exampleDatabase.data.slice().filter((item: DataTable) => {
        let searchStr = (item.obra).toLowerCase();
        return searchStr.indexOf(this.filter.toLowerCase()) != -1;
      });

      // Sort filtered data
      const sortedData = this.sortData(this.filteredData.slice());

      // Grab the page's slice of the filtered sorted data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      this.renderedData = sortedData.splice(startIndex, this._paginator.pageSize);
      return this.renderedData;
    });
  }

  disconnect() { }

  /** Returns a sorted copy of the database data. */
  sortData(data: DataTable[]): DataTable[] {
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number | string | Date = '';
      let propertyB: number | string | Date = '';

      switch (this._sort.active) {
        case 'id': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'foto': [propertyA, propertyB] = [a.foto, b.foto]; break;
        case 'obra': [propertyA, propertyB] = [a.obra, b.obra]; break;
        case 'st': [propertyA, propertyB] = [a.st, b.st]; break;
        case 'folio': [propertyA, propertyB] = [a.folio, b.folio]; break;
        case 'profesional': [propertyA, propertyB] = [a.profesional, b.profesional]; break;
        case 'date': [propertyA, propertyB] = [a.date, b.date]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

这是我的服务

import { Injectable } from '@angular/core';
import { Headers, RequestOptions, RequestMethod, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import { DataTable } from './data-table';

@Injectable()
export class DataTableService {
  private Url = 'http://127.0.0.1:8000';  // URL to web api
  private headers = new Headers({ 'Content-Type': 'application/json' });
  constructor(private http: Http) { }

  printRequest(url, headers, options): void {
    console.log("[url request] ", url);
    console.log("[headers] ", this.headers);
    console.log("[options] ", options);
  }

  getPhoto(id: string): string {
    return id;
  }

  getData(start: string, end: string, obra: string, st: string, folio: string, profesional: string): Promise<DataTable[]> {
    const url = `${this.Url}/server/datatable/`;
    console.log("url -> ", url);
    const options = new RequestOptions({
      headers: this.headers,
    });

    const body = JSON.stringify({ start, end, obra, st, folio, profesional })
    return this.http
      .post(url, body, options)
      .toPromise()
      .then(response => response.json().data as DataTable[])
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}

0 个答案:

没有答案