【问题标题】:Delete option for user if he is the owner of the perticular property如果用户是特定属性的所有者,则删除用户选项
【发布时间】:2018-10-30 13:40:22
【问题描述】:

如果用户创建了特定的展览,我想为他显示删除选项。我正在从 getCurrentUser 服务获取当前用户 ID,并且我正在获取一组展品,其中包含一个字段“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>
----------------------------------------

有人可以帮我弄清楚吗?

【问题讨论】:

    标签: html arrays angular typescript angular-ng-if


    【解决方案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 的更改检测。

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

    希望这会有所帮助!

    【讨论】:

    • @John..我正在尝试按照你说的做,但我仍然无法做到。我存储了所有展品的用户 ID,然后尝试匹配条件,当我将其放入 HTML 时,删除选项已用于所有展品。我只有一个由当前用户创建的展览,并且仅针对该展览,我想要删除选项。是否可以通过其他方式做到这一点?谢谢你的建议..
    • @RuchirNaphade 我在回答中包含了一个示例。我省略了this.canDelete 的需要,而是直接在html 中比较exhibit.idcurrentUser.id。让我知道这是否有帮助!
    • John 是对的,当您必须考虑组件子部分的多种行为时,您不能只使用一个变量。您必须创建一个包含每个案例的删除状态的对象数组。像这样:allmycase = [{ id: "A, title: "AAA", delete: false }, {}...]...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多