Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何使用异步管道检查视图中渲染的可观察对象的长度_Angular_Typescript_Rxjs - Fatal编程技术网

Angular 如何使用异步管道检查视图中渲染的可观察对象的长度

Angular 如何使用异步管道检查视图中渲染的可观察对象的长度,angular,typescript,rxjs,Angular,Typescript,Rxjs,我使用SpringBootREST创建了一个rest端点,以获取所有员工的列表(get)并注册一名员工(POST)。 因此,我决定创建一个组件,在该组件中,我有一个表单在顶部注册员工,并在下面呈现所有员工 import { BrowserModule } from "@angular/platform-browser"; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { Com

我使用SpringBootREST创建了一个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);


从“@angular/platform browser”导入{BrowserModule}”;
从“@angular/platformBrowserDynamic”导入{platformBrowserDynamic};
进口{
组成部分,
NgModule,
可注射,
奥尼特
}从“@角度/核心”;
从“@angular/common/http”导入{HttpClientModule,HttpClient,HttpHeaders};
从“rxjs/Observable”导入{Observable};
进口{
地图,开关地图,点击
}来自“rxjs/运营商”;
@组成部分({
选择器:“重述应用程序”,
模板:`
`
})
类RecapAppComponent{
}
@NGD模块({
导入:[BrowserModule,HttpClientModule],
声明:[RecappComponent、EmployeeDetailsFormComponent、EmployeeListViewComponent、LoadingViewComponent],
引导:[RecapAppComponent],
提供者:[雇员服务]
})
导出类主模块{
}
platformBrowserDynamic().bootstrapModule(MainModule);
然后开始,我开始创建我的服务,用域模型处理get和post请求,如下所示

//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
}


//将其用于雇员数组(2)
班级员工{
构造函数(公共id:number,
public firstName:string,
public lastName:String,
公共电子邮件:字符串){}
}
//我从端点(1)得到这个
班级反应{
建造商(公共状态:编号,
公共消息:string,
公共数据:any){};//我得到一个雇员[]
}
@可注射()
出口级雇员服务{
apiRoot:字符串=”http://localhost:8080";
APIRL:string=`${this.apiRoot}/employees/`
构造函数(私有restHttpClient:HttpClient){}
//所以我创建了一个GET服务,它返回一个可观察的(3)
getAllEmployees():可观察{
log(“In get service”+this.apirl);
//我必须在浏览器中将CORS设置为未禁用(4)
let headers=new-HttpHeaders({'Access-Control-Allow-Origin':'*',
“访问控制允许方法”:“POST、GET、OPTIONS、DELETE、PUT”,
“访问控制最大年龄”:“1000”,
“访问控制允许标头”:“x-requested-with,内容类型,来源,授权,接受,客户端安全令牌”});
//我提出get请求,并且具有可观察性(5)
让check=this.restHttpClient.get(this.apiURL,{headers});
//我将其传递给这个操作符,该操作符从中提取employees数组
//响应对象并返回雇员数组(6)
让我们仔细检查一下(
映射(响应=>{
if(response.data.length==0){
console.log(response.data.length);
返回响应数据;
}否则{
返回response.data.map(employeeJsonOb=>{
返回新员工(employeeJsonOb.id,
employeeJsonOb.firstName,
employeeJsonOb.lastName,
employeeJsonOb.email)
});
}
}));
返回双重检查;
}
//尚未实施
注册雇员(雇员:雇员){}
}
@组成部分({
选择器:“员工列表视图”,
模板:`
(9)
没有发现任何记录

    (8)
  • {{employee.firstName}
` }) 类EmployeeListViewComponent实现OnInit{ 员工:可观察; 私有加载:boolean=false; 构造函数(私有employeeService:employeeService){} //然后我用onInit钩子把所有员工都找来 //启动时,如果有。(7) 恩戈尼尼特(){ console.log(“输入onInit”); this.employees=this.employeeService.getAllEmployees(); } } @组成部分({ 选择器:“员工详细信息表单”, 模板:` 表格在这里

` }) 类EmployeeDetailsFormComponent{ //尚未实施 }
我一直无法解决这一点


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

您可以执行以下操作:

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

没有发现任何记录

0
是一个错误的值,因此不需要进行显式比较


将捕获由于
(employees | async)
未定义/null而不是空数组而导致的任何问题。

我猜您收到的错误消息类似于
length$不是未定义的属性?