角度范围问题

时间:2018-07-27 08:57:52

标签: angular

我正在使用Angular客户端应用程序

  1. Angular CLI:6.0.3
  2. 节点:8.9.4
  3. 操作系统:win32 x64
  4. 角度:6.0.3

对于服务器,我已经使用了WEBAPI APP(NET CORE 2.0)

在此组件中,全局var的范围存在问题。 加载页面后,我可以看到datasource和dataSource2,但是看不到nombresFinal(这是从数组和datasource2获取foreach数据的结果),但是如果我使用按钮如何调用findNames(),则可以看到列表nombresFinal。我在做什么错了?

这是我的contact-browser.component.html文件:
<div class="spinner" *ngIf="loadingState; else contactlist">
  <mat-spinner></mat-spinner>
</div>
<ng-template class="contactlist" #contactlist>
  <h2><mat-icon class="example-icon">search</mat-icon>Buscar para la visita con motivo: {{motivo}} </h2>
  <div>
    <mat-form-field appearance="outline">
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Buscar por ID / PASSPORT / DNI">
    </mat-form-field>
  </div>
  <div class="contactlist-container mat-elevation-z8">
    <table mat-table #table [dataSource]="dataSource">
      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Nombre </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>

      <!-- surname Column -->
      <ng-container matColumnDef="surname">
        <th mat-header-cell *matHeaderCellDef> Apellidos </th>
        <td mat-cell *matCellDef="let element"> {{element.surname}} </td>
      </ng-container>

      <!-- dni Column -->
      <ng-container matColumnDef="dni">
        <th mat-header-cell *matHeaderCellDef> ID / PASSPORT / DNI </th>
        <td mat-cell *matCellDef="let element"> {{element.dni}} </td>
      </ng-container>

      <!-- company Column -->
      <ng-container matColumnDef="company">
        <th mat-header-cell *matHeaderCellDef> Empresa </th>
        <td mat-cell *matCellDef="let element"> {{element.company}} </td>
      </ng-container>

      <!-- date Column -->
      <ng-container matColumnDef="fecha">
        <th mat-header-cell *matHeaderCellDef> Fecha </th>
        <td mat-cell *matCellDef="let element"> {{element.fecha | date: 'dd-MM-yyyy' }} </td>
      </ng-container>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
  </div>
  <br/>
  <h2><mat-icon class="example-icon">how_to_reg</mat-icon>Enlace de la visita: </h2>
  <div class="contactlist-container mat-elevation-z8">
    <table mat-table #tableEnlace [dataSource]="dataSource2">
      <ng-container matColumnDef="contactId">
        <th mat-header-cell *matHeaderCellDef> contactId </th>
        <td mat-cell *matCellDef="let element"> {{element.contactId}} </td>
      </ng-container>
      <ng-container matColumnDef="visitId">
        <th mat-header-cell *matHeaderCellDef> visitId </th>
        <td mat-cell *matCellDef="let element"> {{element.visitId}} </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="displayedColumns2"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns2;"></tr>
    </table>
  </div>
  <br/>
  <div *ngIf="isDataAvailable">
    <h2><mat-icon class="example-icon">how_to_reg</mat-icon>Integrantes de la visita: </h2>
    <mat-list>
     <mat-list-item *ngFor="let elemento of nombresFinal">
        <h4 mat-line>-{{elemento}}</h4>
      </mat-list-item>
      <mat-divider></mat-divider>
    </mat-list>
  </div>
  <div mat-dialog-actions>
      <button title="No"  mat-raised-button color="primary" (click)="dialogAux.close()">Cancelar</button>
      <button title="Ver Visitantes"  mat-raised-button color="primary" (click)="findNames()">Ver Visitantes</button>
    </div>
</ng-template>
这是我的contact-browser.component.ts文件:
import { Component, ViewChild, OnInit, Inject } from '@angular/core';
import { IContact } from './../model/contact';
import { IEnlaceVisitContact } from './../model/enlaceVisitContact';
import { MatTableDataSource, MatSnackBar, MatPaginator } from 
@angular/material';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog} from '@angular/material';
import { ConfirmationDialogComponent } from '../confirmation- 
dialog/confirmation-dialog.component';
import { ContactService } from '../services/contact.service';
import { EnlaceService } from '../services/enlace.service';
import { DBOperation } from '../shared/DBOperations';
import { Global } from '../shared/Global';

@Component({
selector: 'app-contact-browser',
templateUrl: './contact-browser.component.html',
styleUrls: ['./contact-browser.component.scss'] })

export class ContactBrowserComponent implements OnInit {
contacts: IContact[];
loadingState: boolean;
isDataAvailable: boolean;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;
array: any;
array2: any;
visitasAux: any;
nombresFinal: any;
contactsFinal: any;
dataSource: any;
dataSource2: any;
visita: number;
contacto: number;
motivo: string;
// set columns that will need to show in listing table
displayedColumns = ['name', 'surname', 'company', 'dni', 'fecha', 'action'];
displayedColumns2 = ['contactId', 'visitId'];


constructor(@Inject(MAT_DIALOG_DATA) public data: any,
 public snackBar: MatSnackBar,
 private _contactService: ContactService,
 private _enlaceService: EnlaceService,
 public dialogAux: MatDialogRef<ContactBrowserComponent>,
 public dialog: MatDialog) {}

ngOnInit() {
  this.loadingState = true;
  this.isDataAvailable = false;
  console.log('app = ngOnInit');
  this.motivo = this.data.visitaActiva.motivo;
  // LOADCONTACTS
  this._contactService.getAllContact(Global.BASE_USER_ENDPOINT + 
 'getAllContact')
 .subscribe(contacts => {
  this.dataSource = new MatTableDataSource<IContact>();
  this.array = contacts;
  });
  console.log('LOADCONTACTS');
  // LOADENLACES

 this._enlaceService.getAllEnlaceVisitContact(Global.BASE_USER_ENDPOINTEnlace 
  + 'getAllEnlaceVisitContact')
  .subscribe(enlace => {
  this.dataSource2 = new MatTableDataSource<IEnlaceVisitContact>();
  this.array2 = enlace;
  this.dataSource2 = this.array2;
  this.dataSource2 = this.dataSource2.filter(x => x.visitId === 
this.data.visitaActiva.id);
 });
 console.log('LOADENLACES');
// this.loadEnlaces();
// this.nombresFinal = this.findNames();
this.visitasAux = this.dataSource2;
console.log(this.dataSource2);
const nombres: string[] = [];
if (this.visitasAux !== undefined)  {
this.visitasAux = this.visitasAux.filter(x => x.visitId === 
this.data.visitaActiva.id);
this.visitasAux.forEach((enlaceElement) => {
  this._contactService.getAllContact(Global.BASE_USER_ENDPOINT + 
 'getAllContact')
  .subscribe(contacts => {
  this.dataSource = new MatTableDataSource<IContact>();
  this.array = contacts;
  });
  console.log(this.contacts);
  console.log(this.array);
  this.array.forEach(function(personaElement) {
    if (enlaceElement.contactId === personaElement.id) {
      let nombre = '';
      nombre = personaElement.name +  ' ' + personaElement.surname;
      nombres.push(nombre);

     } else {
      console.log(enlaceElement);
      console.log(personaElement);
     }
  });
});
this.nombresFinal = nombres;
}
this.loadingState = false;
if (this.nombresFinal !== undefined) {
  this.isDataAvailable = true;
 }
}
// END ngOnInit

findNames(): string[] {
this.visitasAux = this.dataSource2;
const nombres: string[] = [];
if (this.visitasAux !== undefined)  {
this.visitasAux = this.visitasAux.filter(x => x.visitId === 
this.data.visitaActiva.id);
this.visitasAux.forEach((enlaceElement) => {
  this._contactService.getAllContact(Global.BASE_USER_ENDPOINT + 
'getAllContact')
  .subscribe(contacts => {
  this.dataSource = new MatTableDataSource<IContact>();
  this.array = contacts;
  });
  this.array.forEach(function(personaElement) {
    if (enlaceElement.contactId === personaElement.id) {
      let nombre = '';
      nombre = personaElement.name +  ' ' + personaElement.surname;
      nombres.push(nombre);

     } else {
      console.log(enlaceElement);
      console.log(personaElement);
     }
  });
});
this.nombresFinal = nombres;
this.isDataAvailable = true;
return this.nombresFinal;
 } else {
console.log ('Estoy sin datos de nombresFinal');
 }

applyFilter(filterValue: string) {
 filterValue = filterValue.trim(); // Remove whitespace
 filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to 
 lowercase matches
 this.dataSource = this.array;
 this.dataSource = this.dataSource.filter(x => x.dni.toLowerCase() === 
 filterValue);
 }
}
这是contact.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpErrorResponse } from 
'@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { IContact } from '../model/contact';
const httpOptions = {headers: new HttpHeaders({'Content-Type': 
'application/json'})};

 @Injectable()
 export class ContactService {
 constructor(private http: HttpClient) { }
 // get all contact data
 getAllContact(url: string): Observable <IContact[]> {
 return this.http.get <IContact[]> (url).pipe(catchError(this.handleError));
 }
}
这是enlace.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpErrorResponse } from 
'@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { IEnlaceVisitContact } from '../model/enlaceVisitContact';
const httpOptions = {headers: new HttpHeaders({'Content-Type': 
'application/json'})};

 @Injectable({providedIn: 'root'})
  export class EnlaceService {

  constructor(private http: HttpClient) { }
  // get all IEnlaceVisitContact data
  getAllEnlaceVisitContact(url: string): Observable <IEnlaceVisitContact[]> {
  return this.http.get <IEnlaceVisitContact[]> 
  (url).pipe(catchError(this.handleError));
  }
 }

我注意到在页面加载时,dataSource2和数组(全局变量)是可访问的,但在加载页面之前不是。

0 个答案:

没有答案