在空桌

时间:2018-06-12 19:54:13

标签: angular angular-material

我是Angular的新人。我实现了材料表,我从服务中加载数据并调用组件,如下所示:

 ngOnInit() {
    this.UsuariosService.getUser().subscribe(results => {
      if (!results) {
        return;
      }
      this.dataSource = new MatTableDataSource(results);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;

    });
  }

它工作正常,但现在我想在表空时显示消息,所以我尝试:

HTML:

<mat-table>
    //content there
</mat-table>
  <div *ngIf="noResults$ | async"> No results</div>

然后在组件中这样:

ngOnInit() {
    this.UsuariosService.getUser().subscribe(results => {
      if (!results) {
        return;
      }
      this.dataSource = new MatTableDataSource(results);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      var noResults$ = results.map(d => d.length === 0).startWith(false);

    });
  }

但我得到3个错误:

错误1(Html):

  

标识符&#39; noResults $&#39;没有定义。组件声明,   模板变量声明和元素引用不包含   这样的成员

我不知道为什么,因为我在组件

上声明了noResults $

错误2(组件):

  消息:&#39;属性&#39;长度&#39;类型&#39;用户&#39; <&#39;

上不存在

为什么&#39;长度&#39;寻找财产?假设长度是一种在服务中寻找注册的方法

错误3(组件):

  

财产&#39; startWith&#39;在&#39; boolean []&#39;。

类型中不存在

我对此错误一无所知

非常感谢帮助。此致

完整组件:

import {
  Component,
  Input,
  OnInit,
  ViewEncapsulation,
  ViewChild,
  ElementRef
} from "@angular/core";
import { ModalDismissReasons, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
import { ScriptLoaderService } from "../../../../../_services/script-loader.service";
import { ToastrService } from "ngx-toastr";

import { UsuariosService } from "../../../../../_services/usuarios.service";
import { Observable } from "rxjs/Observable";
import {
  DataSource,
  CollectionViewer,
  SelectionModel
} from "@angular/cdk/collections";
import { BehaviorSubject } from "rxjs";
import {
  MatSort,
  MatSortable,
  MatTableDataSource,
  MatPaginator,
  MatPaginatorIntl
} from "@angular/material";


import { SwalComponent } from "@toverux/ngx-sweetalert2";

@Component({
  selector: "usuarios",
  templateUrl: "./usuarios.component.html",
  encapsulation: ViewEncapsulation.None
})
export class UsuariosComponent {
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild("filter") filter: ElementRef;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild("deleteSwal") private deleteSwal: SwalComponent;

  // Bootstrap switch
  public yes: string = "SI";
  public no: string = "NO";
  public green: string = "green";
  public gray: string = "gray";
  public disabled: boolean = false;
  public status: boolean = false;
  public normal: string = "small";
  //end Bootstrap switch

  public eliminar: string = "ELIMINAR";
  public cancelar: string = "CANCELAR";
  public red: string = "red";


  selection = new SelectionModel<string>(true, []);
  dataSource;

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  displayedColumns = [
    "id",
    "nombre",
    "apellido",
    "email",
    "perfil",
    "ultimoLogin",
    "activo",
    "action"
  ];

  constructor(
    private _script: ScriptLoaderService,
    private toastr: ToastrService,
    private UsuariosService: UsuariosService
  ) {}

  ngOnInit() {
    this.UsuariosService.getUser().subscribe(results => {
      if (!results) {
        return;
      }
      this.dataSource = new MatTableDataSource(results);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      var noResults$ = results.map(d => d.length === 0).startWith(false);

    });
  }

  onFlagChange(event, { id }) {
    const body: any = {
      usuarioId: id,
      activo: event
    };
    this.UsuariosService.postSwitch(body).subscribe(
      () => {
        //React to your HTTP request success
        this.toastr.success("El Usuario se ha actualizado correctamente.");
      },
      err => {
        this.toastr.error("Ocurrió un error al actualizar Usuario.");
        //React to your HTTP request error
      }
    );
  }
  deleteUser(userid) {
    debugger;
    this.UsuariosService.eliminar(userid).subscribe(
      () => {
        this.toastr.success("El usuario se ha eliminado con éxito.");
      },
      err => {
        this.toastr.error("Ocurrió un error al eliminar Usuario.");
      }
    );
  }
}

更新

第一个问题解决了将noResults$添加为public noResults$: any;

的问题

并调用方法简单如下:

this.noResults$ = results.map(d => d.length === 0).startWith(false);

3 个答案:

答案 0 :(得分:1)

map函数用于转换数组中的每个项目。

当你这样做时:

results.map(d => d.length === 0).startWith(false);

这是试图检查每个用户的length属性。最后,它尝试在新数组上使用startWith,但数组没有startWith函数。

假设你只想检查数组是否为空,你可以这样做:

this.noResults = d.length === 0;

请注意,我没有使用noResults$作为变量名称。如果名称是Observable,名称应仅以$结尾,但在这种情况下不是。

答案 1 :(得分:0)

1)HTML在HTTPServer((host, port), SimpleHTTPRequestHandler)挂钩呈现之前正在寻找变量noResults$。 您需要在组件呈现之前(构造函数之前)定义它并在OnInit函数中引用它,如此

OnInit

2&amp; 3)如果使用Angular HTTPClient来生成get请求,则不需要映射响应,这可能导致这两个错误。您应该运行以下内容进行测试,以查看分配给ngOnInit() { this.UsuariosService.getUser().subscribe(results => { if (!results) { return; } this.dataSource = new MatTableDataSource(results); this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; this.noResults$ = results.map(d => d.length === 0).startWith(false); }); } 的内容。

d

答案 2 :(得分:0)

您可以为else设置ngIf并设置模板在这种情况下将呈现的内容。

<mat-table *ngIf="dataSource.data; else placeholder">
    //content there
</mat-table>
<ng-template #placeholder>
   <div> No results</div> 
</ng-template>

您可以在此处找到更多信息https://toddmotto.com/angular-ngif-else-then#ngif-and-else