使用在智能组件内部使用2个参数的方法来重构智能/哑组件中的组件

时间:2018-06-23 09:00:37

标签: angular refactoring

我试图按照我的角度项目中的智能/笨拙组件模式来重构代码,但我坚持以下情况:

我有一个组件CategoriesComponent,其中包含一个我想移至哑组件CategoriesTableComponent的表。

因此,我将选项卡模板移动到了哑巴组件,并使用如下输入和输出将智能组件链接到了哑巴组件:

categories.component.ts(智能组件)

export class CategoriesComponent implements OnInit {

  @Input() theme: Theme;

  categories$: Observable<Category[]>;

  [...]

  /**
   * Delete a selected category on the server and the data store
   * @param category the category to delete
   */
  onDeleteCategory(themeId: string, category: Category) {
    this.categoryStoreService.deleteCategory(themeId, category);
  }
}

categories.component.html(智能组件)

<div class="container" *ngIf="theme">

  [...]

  <app-categories-table [theme]="theme"
                        [categories]="categories$ | async"
                        (deleteCategory)="onDeleteCategory($event)"></app-categories-table>
</div>

categories-table.component.ts(哑组件)

export class CategoriesTableComponent {

  @Input() theme: Theme;
  @Input() categories: Category[];
  @Output() deleteCategory: EventEmitter<{themeId: string, category: Category}> = new EventEmitter();

  constructor() { }

}

categories-table.component.html(哑组件)

<div class="row">
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
        <tr>
          <th>Name</th>
          <th>Description</th>
          <th></th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let category of categories">
          [...]
          <td>
            <button class="btn btn-outline-dark" type="button" title="delete category" (click)="deleteCategory.emit({theme._id, category})">
              <i class="fas fa-trash"></i>
              Delete
            </button>
          </td>
          [...]

但是我在控制台中看到以下错误消息:

  

未捕获的错误:模板解析错误:解析器错误:缺少预期   :位于[deleteCategory.emit({theme._id,category})]中的第27列   ng:///AppModule/CategoriesTableComponent.html@26:87(“               错误   -> =“ deleteCategory.emit({theme._id,category})”>                        ”):ng:///AppModule/CategoriesTableComponent.html@26:87

我知道它在deleteCategory.emit({theme._id, category})声明中,但是我想知道是否有一种方法可以在不对category-table.component.ts

中编写其他方法的情况下进行内联。

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

错误消息告诉您

中缺少冒号
deleteCategory.emit({theme._id, category})

确实,这不是有效的JavaScript。正确的代码是

deleteCategory.emit({themeId: theme._id, category: category})