1

我将项目(数据)传递给是否显示某个视图。但是,当我刷新页面时,它会破坏页面。这个 div 有效<p class="admin">{{ project?.name }}</p>。但是下面的代码,当我单击刷新时会产生错误。当我单击刷新时,错误是无法读取未定义的属性“material_projects”。我如何在这个安全导航中通过*ngIf="getProjectType(projects) === 'mat_exist'"

<p *ngIf="getProjectType(projects) === 'mat_exist'">
      <ngb-alert type="success">
        You Already Have An Existing Material/s On This Project. <br>
        You Can Add More Material/s Below.
      </ngb-alert>
    </p>
    <p *ngIf="getProjectType(projects) === 'service_exist'">
      <ngb-alert  type="info">
        You Already Have An Existing Service/s On This Project. <br>
        You Can Add More Service/s Below.
      </ngb-alert>
    </p>

ts

 ngOnInit() {
        this.route.params 
          .subscribe((params: Params) => { 
          this.id = +params['id']; 
          this.projectsService = this.injector.get(ProjectsService);
          this.projectsService.getProject(this.id)
          .subscribe(
              (data:any) => {
                this.projects = data;
                console.log(data);

              },
              error => {
                alert("ERROR");
              })
          }); 
}

ts

public getProjectType(project): 'mat_exist' | 'mat_new' | 'service_exist' | null {
        return project.material_projects.length > 0 ? 'mat_exist'
            : project.project_services.length > 0 ? 'service_exist'
            : null;
    }
4

1 回答 1

0

由于存在project未定义的可能性,因此getProjectType函数应考虑到这一点:

public getProjectType(project): 'mat_exist' | 'mat_new' | 'service_exist' | null {
  if (!project) return null;
  ...
}

也可以将此条件移至ngIf

<p *ngIf="projects && getProjectType(projects) === 'mat_exist'">
...

或者ngIf可以向父元素添加额外的;如果没有,则ng-container可以使用:

<ng-container *ngIf="projects">
    <p *ngIf="getProjectType(projects) === 'mat_exist'">
    ...
于 2017-10-22T09:42:23.013 回答