在angular2中使用小吃店(entryComponents)时如何发出事件

How to emit event when using snack-bar (entryComponents) in angular2

这里我有一个方法'confirmSth',动态加载了一个组件'SnackCheckBoxComponent'。

我想知道我是否可以在我的 OrderDetailComponent 中得到一些消息来区分我点击的是哪个按钮和 SnackCheckBoxComponent 以便决定 confirmSth return true or false.

//...
import { MdSnackBar, MdSnackBarRef } from '@angular/material';

export class OrderDetailComponent {

  constructor(public snackBar: MdSnackBar) {

  confirmSth(): boolean {

    // ...condition
    if (condition) return true

    this.snackBarRef = this.snackBar.openFromComponent(SnackCheckBoxComponent, { duration: 50000 })
    this.snackBarRef.instance.snackBarRefCheckComponent = this.snackBarRef

    // I would like to know If I can get some msg here to distinguish which button i clicked so to decide return true or false.

  }

}

@Component({
  selector: 'snack-check-box',
  templateUrl: './snack-check-box.html',
  styleUrls: ['./snack-check-box.css'],
})
export class SnackCheckBoxComponent {
  public snackBarRefCheckComponent: MdSnackBarRef<SnackCheckBoxComponent>

  private onCancel() {
    alert('clicked option 1');
    this.snackBarRefCheckComponent.dismiss();
  }

  private onSubmit() {
    alert('clicked option 2');
    this.snackBarRefCheckComponent.dismiss();
  }
}

这是我的'./snack-check-box.html'

<span>overloaded, whether to continue xxx</span>

<a (click)="onSubmit()">yes</a>
<a (click)="onCancel()">no</a>

SnackCheckBoxComponent 中创建两个 RxJS 主题并使用绑定函数调用 next 值;这是一个只有提交功能的例子。

export class SnackCheckBoxComponent {
  public submit$ = new Subject<void>()
  public onSubmit() { this.submit$.next(null) }
}

现在您可以通过 OrderDetailComponent 订阅这些活动:

this.snackBarRef.instance.submit$.take(1).subscribe(() => {
  // handle submission here
}

请注意,由于我已经使用 .take(1),您不必手动取消订阅。流将在拿走我们期望的一个且唯一的项目后结束。或者,您可以在此处使用 Observable#toPromise


作为旁注,您的 onCancelonSubmit 必须是 public,因为您是从模板(在 class 之外)访问它们。模板当前未在 JIT 模式下进行类型检查,但您的代码在 AOT 中会失败,AOT 正在成为 Angular 应用程序的标准。