angular - 如何使用异步管道检查在 View 中呈现的 Observable 的长度

标签 angular typescript rxjs

我使用 spring boot rest 创建了一个 rest 端点,以获取所有员工的列表 (GET) 并注册一名员工 (POST)。 所以我决定创建一个组件,其中我有一个表单来在顶部注册员工,并在下方呈现所有员工。

import { BrowserModule } from "@angular/platform-browser";
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
  Component,
  NgModule,
  Injectable,
  OnInit
} from "@angular/core";
import { HttpClientModule, HttpClient, HttpHeaders } from "@angular/common/http";
import {Observable} from 'rxjs/Observable';
import {
  map, switchMap, tap
} from "rxjs/operators";

@Component({
  selector: "recap-app",
  template: `
<employee-details-form></employee-details-form>
<employee-list-view></employee-list-view>
  `
})
class RecapAppComponent{

}


@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [RecapAppComponent, EmployeeDetailsFormComponent, EmployeeListViewComponent, LoadingViewComponent],
  bootstrap: [RecapAppComponent],
  providers: [EmployeeService]
})
export class MainModule {

}

platformBrowserDynamic().bootstrapModule(MainModule);


然后开始,我开始创建我的服务来处理域模型的获取和发布请求,如下所示

//Use this for the employee array (2)
class Employee{
  constructor(public id : number,
    public firstName : string,
    public lastName : String,
    public email : string){}
}

//I get this from the endpoint (1)
class Response{
  constructor(public status: number,
    public message : string,
    public data : any){};//I get an Employee[]
}

@Injectable()
export class EmployeeService{

  apiRoot: string = "http://localhost:8080";
  apiURL: string = `${this.apiRoot}/employees/`
  constructor(private restHttpClient: HttpClient) {}

  //So I created a GET service which returns an observable (3)

  getAllEmployees() : Observable<Employee[]> {
    console.log("In get service " + this.apiURL);

    //I had to set CORS as its not disabled in my browser (4)

    let headers = new HttpHeaders({'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods' :  'POST, GET, OPTIONS, DELETE, PUT',
    'Access-Control-Max-Age' : '1000',
    'Access-Control-Allow-Headers' : 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token'});

    //I make the get request, and with that observable   (5)

    let check = this.restHttpClient.get<Response>(this.apiURL,{headers});

    //I pass it through this operator which extracts the employees array from 
    // the response object and returns an employee array (6)

    let doubleCheck = check.pipe(
      map(response => {
        if(response.data.length === 0){
          console.log(response.data.length);
          return response.data;
        }else{
          return response.data.map(employeeJsonOb => {
            return new Employee(employeeJsonOb.id,
              employeeJsonOb.firstName,
            employeeJsonOb.lastName,
          employeeJsonOb.email)
          });
        }
    }));
    return doubleCheck;
  }
  //yet to be implemented
  registerNewEmployee(employee : Employee){}
}

@Component({
  selector: "employee-list-view",
  template: `

  <!--But when I got no records I wanted to display this div
   but I couldn't --> (9)

  <div *ngIf = "employees.length$ === 0">
    <p> No records found </p>
  </div>
  <div>
    <ul class="list-group">
      <!--Then when I iterated by adding some employees
          I was able to see the names--> (8)
      <li class="list-group-item" *ngFor = "let employee of employees | async">
        {{employee.firstName}}
      </li>
    </ul>
  </div>
  `
})
class EmployeeListViewComponent implements OnInit{

  employees : Observable<Employee[]>;
  private loading: boolean = false;
  constructor(private employeeService: EmployeeService) {}

  //Then I used the onInit hook to try to fetch all employees 
  //on startup if there were any. (7)
  ngOnInit() {
    console.log("Entered onInit");
    this.employees = this.employeeService.getAllEmployees();
  }
}

@Component({
  selector: "employee-details-form",
  template: `
  <div>
  <p>Form goes here</p>
  </div>
  `
})
class EmployeeDetailsFormComponent{
//Yet to be implemented
}


我一直无法解决第 (9) 点。

如有任何帮助,我们将不胜感激。

最佳答案

您可以执行以下操作:

<div *ngIf="!(employees | async)?.length">
  <p> No records found </p>
</div>

0 是一个伪值,因此您不需要进行显式比较。

question mark将捕获由 (employees | async) 未定义/空而不是空数组引起的任何问题。

关于angular - 如何使用异步管道检查在 View 中呈现的 Observable 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152108/

相关文章:

javascript - 在 typescript 中将 React.Component 状态设置为等于 this.props 值是否存在问题?

javascript - 如何发出每个第 n 个值?

javascript - 使用 Rxjs 并行调用同时延迟的请求 block ?

angular - 需要返回类型的箭头函数的 ESLint 规则

javascript - 如何在 TypeScript 中声明数组对象

在 axis.tickFormat() 中使用 d3.timeFormat 时出现 TypeScript 错误

javascript - 使用 forEach Angular 4 的多个 POST 请求

javascript - Angular 应用程序无法运行并显示无效配置错误

javascript - 即使不在 console.log 中,值也为 null (...)

angularjs - tsd 安装和 tsd 查询命令返回 "zero results "消息