Angular 4 事件发射器未在订阅时捕获任何内容

Angular 4 Event Emitter not catching anything on subscribe

一个月前我发布了一个小的library,它只允许显示加载动画。

为此,我的用户只需将 <ng-load></ng-load> 添加到他们的模板并在其组件中注入 LoadService 并调用 loadService.animate(true)(或 false)。

在图书馆方面,我做了以下事情:

为我服务:

@Injectable()
export class LoadService {
  // My event emitter
  @Output() animating: EventEmitter<any> = new EventEmitter();

  constructor() {}

  // Method called by the user to display the animation,
  // emits the value passed as parameter
  public animate(val: boolean) {
    this.animating.emit(val);
  }

  getValue(): any {
    return this.animating;
  }
}

在我的组件中:

@Component({
    selector: 'ng-load',
    templateUrl: './load.component.html',
    styleUrls: ['./load.component.css']
})
export class LoadComponent implements OnInit {      
    animate: boolean;

    constructor(public loadService: LoadService) {}

    ngOnInit(): void {
        // Listen to our event emitter
        this.loadService.getValue().subscribe((status: boolean) => {
            this.animate = status;
        });
    }
}

我的 HTML 模板只有一个 <div *ngIf="animate"> 来显示或隐藏 CSS 动画。

所以我的事件发射器发出了我的用户提供给 animate 的东西,我的布尔值应该在我的组件中发生变化,或者一个月前就发生了变化。

出于某种原因,我的事件发射器上的订阅没有捕捉到任何东西。

EventEmitters有变化吗?我是否以错误的方式使用它们?

由于您使用的是原始数据类型boolean,因此可能会出现对象引用保持不变的情况,因此不会触发订阅。

  • 所以使用复杂对象

     let animation ={
          allowAnimation : true/false
     };
     this.animating.emit(animation); // might trigger the subscription 
    
  • 增量计数器(数字)

     this.animating.emit(i++); 
    

注意:如果第一种情况没有触发,那么您可以更改引用并发出,这将导致订阅触发。

您的代码有多个问题。首先,@Output 用于组件而不是服务。其次,您正在订阅 getValue(),它不是 return Observable,订阅无法工作。第三,如果您希望您的服务将数据推送给订阅者,请使用 Rx.Subject,因为 EventEmitter 只是 Subject 之上的另一层抽象,其行为将来可能会发生变化。