如果用户是特定属性的所有者,则删除该用户的选项

时间:2018-05-20 21:49:18

标签: html arrays angular typescript ngif

我想为用户创建删除选项,如果他已经创建了特定的展览。我从getCurrentUser服务获取当前用户ID,我得到一系列展品,其中thre是一个字段“userId”。

我正在尝试匹配当前用户的id和来自Exhibits数组的userId,如果有匹配,那么只有用户才能获得针对特定展览的删除选项,但我无法以正确的方式进行。

以下是我的代码:

-------------------------------------------------------------------------------
  ngOnInit() {
    this.getCurrentUser();
    this.getIsSupervisor();
    this.spinnerService.show();
    let allRoutesOption = Route.emptyRoute();
    allRoutesOption.title = 'ALL';
    this.routes = [allRoutesOption];

    this.getAllExhibits();

    this.routeService.getAllRoutes(1, 100)
      .then(
        data => this.routes = this.routes.concat(data.items)
      ).catch(
        error => console.error(error)
      );

    this.getPage(1);

  }

  ngOnDestroy() {
    this.spinnerService.hide();
  }

  getIsSupervisor() {
    this.supervisorGuard.isSupervisor().then(
      (response: boolean) => {
        this.isSupervisor = response;
      });
  }

  getCurrentUser() {
    this.userService.getCurrent()
      .then(
        (response) => {
          this.currentUserId = response.id;
          this.exhibitService.getAllExhibits(1, this.maxNumberOfMarkers)
            .then(
              (data) => {
                this.allExhibits = data.items;
                for (let exhibit of this.allExhibits) {
                  this.exhibitsUserIds.push(exhibit.userId);
                    if (this.exhibitsUserIds !== this.currentUserId) {
                      this.canDelete = false;
                    } else {
                      this.canDelete = true;
                    }
                }
              }
            );
        }
      );
  }
-------------------------------------------------------------------------------

我的Html:

----------------------------------------
  <md-nav-list>
    <md-list-item [routerLink]="['/mobile-content/exhibits/view', exhibit.id]" ng-blur="true" *ngFor="let exhibit of exhibits | paginate: { id: 'server',
                                                                itemsPerPage: exhibitsPerPage,
                                                                currentPage: currentPage,
                                                                totalItems: totalItems }">
      <img md-list-avatar *ngIf="previewsLoaded && previews.has(exhibit.id); else exhibitIcon" [src]="previews.get(exhibit.id)"
        alt="{{ 'image preview' | translate }}" [ngStyle]="{'width.px': 48, 'height.px': 48}">
      <ng-template #exhibitIcon>
        <md-icon md-list-icon class="type-icon" [ngStyle]="{'font-size.px': 40, 'height.px': 40, 'width.px': 40}">place</md-icon>
      </ng-template>
      <h2 md-line>{{ exhibit.name }} ({{ exhibit.status | translate }})
        <hip-star-rating class="fix-position" *ngIf="exhibit.ratings" [rating]='exhibit.ratings' [exhibitId]='exhibit.id'></hip-star-rating>
      </h2>
      <p md-line>{{ exhibit.description }}</p>
      <p md-line>
        <span class="latitude">{{ exhibit.latitude }}</span>,
        <span class="longitude">{{ exhibit.longitude }}</span>
      </p>
      <p *ngIf="exhibit.tags.length > 0" md-line>
        <span *ngFor="let tag of exhibit.tags" class="tag-name">{{ tag }}</span>
      </p>

      <button md-icon-button click-stop-propagation color="primary" [routerLink]="['/mobile-content/exhibits/edit', exhibit.id]"
        title="{{ 'edit' | translate }}">
        <md-icon>{{ !inDeletedPage ? 'edit' : 'remove_red_eye'}}</md-icon>
      </button>
      <div *ngIf="canDelete">
        <button md-icon-button click-stop-propagation color="warn" (click)="deleteExhibit(exhibit)" *ngIf="!exhibit.used && !inDeletedPage"
          title="{{ 'delete' | translate }}">
          <md-icon>delete_forever</md-icon>
        </button>
      </div>
    </md-list-item>
----------------------------------------

有人可以帮我解决一下吗?

1 个答案:

答案 0 :(得分:1)

我自己是Angular的新手,但也许我仍然可以提供帮助。我注意到一些可能导致问题的事情。

首先

当您在this.allExhibits内进行迭代时,我注意到this.canDelete只是您在每次迭代后重新分配的一个值。到最后它只代表最后一次展览的“可删除性”。

也许您可以创建某种对象或数组来映射this.allExhibits的for..of迭代。这样,您可以存储每个已解析的this.canDelete值,而不会在每次迭代时覆盖它。

example.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  currentUser:object = {
    name: 'User A',
    id: 'A'
  };

  exhibits:object[] = [
    {
      title: 'Exhibit A',
      id: 'A'
    },
    {
      title: 'Exhibit B',
      id: 'B'
    },
    {
      title: 'Exhibit C',
      id: 'C'
    }
  ];

  constructor() { }

  deleteExhibit(index) {
    this.exhibits = this.exhibits.filter((_, i) => i != index);
  }
}

example.component.html

<div *ngFor="let exhibit of exhibits; let i=index">
  <h3>{{exhibit.title}}</h3>
  <button *ngIf="exhibit.id == currUser.id" (click)="deleteExhibit(i)">DELETE</button>
  <hr/>
</div>

其次

我认为getCurrentUser()是在组件实例化时发生的事情。在这种情况下,* ngIf必须等待this.canDelete的已解析值才能显示或隐藏删除按钮。

由于getCurrentUser()似乎在组件初始呈现视图后的某个时间解析,因此设置this.canDelete的值可能不会触发Angular的更改检测。

在解析ChangeDetectorRef.detectChanges()的最终值后,或许尝试this.canDelete。 ChangeDetectorRef可从@angular/core导入,并可在组件的构造函数中实例化:constructor(private changeDetectorRef:ChangeDetectorRef) {}

希望这有帮助!