简体   繁体   English

Angular2:如何为调用异步方法的按钮创建加载指令?

[英]Angular2: How to create a loading directive for a button that call an async method?

I want to create a directive for a button/link to replace its inner text by a loader when it's clicked and to re-set its inner text when the call has succeed or fail. 我想创建一个按钮/链接的指令,以便在单击时通过加载器替换其内部文本,并在调用成功或失败时重新设置其内部文本。

Here is how I start: 我是这样开始的:

HTML : HTML:

<button (click)="update()" asyncLoader >Update</button> 

Directive : 指令:

import {
  Directive,
  Input,
  ElementRef,
  AfterViewInit,
  Output,
  EventEmitter,
  HostListener,
} from '@angular/core';


@Directive({
  selector: '[asyncLoader]'
})
export class ActionAsyncLoader {

  text: string;
  // @Output() valueChanged = new EventEmitter();

  constructor(private elementRef: ElementRef) {
  }

  ngOnInit(){
    this.text = this.elementRef.nativeElement.innerHTML;
    // console.log('this.text', this.text);
  }

  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log('click async btn', btn);
    btn.innerHTML = 'Loading';
  }
}

Here the clicked element replaces its text by 'Loading'. 这里点击的元素用'Loading'替换它的文本。

Question : Since the async method is set in a component, How to listen to the callback from here? 问题:由于异步方法是在组件中设置的,如何从这里收听回调?

For now, i just emit an event on success and fail, then suscribe to it in the directive... and i pass a input in the directive to be sure it matches the callback. 现在,我只是在成功时发出一个事件而失败,然后在指令中对它进行控制......我在指令中传递一个输入以确保它与回调相匹配。

HTML : HTML:

<button (click)="update()" asyncLoader='updateXYZ' >Update</button> 

Directive : 指令:

@Directive({
  selector: '[asyncLoader]'
})
export class ActionAsyncLoader {

  @Input('asyncLoader') asyncLoader: string;
  text: string;
  // @Output() valueChanged = new EventEmitter();

  constructor(private elementRef: ElementRef,
              private eventsService: EventsService) {
    eventsService.onCallbackAsync.subscribe(obj => this.onCallbackAsync(obj));
  }

  ngOnInit(){
    this.text = this.elementRef.nativeElement.innerHTML;
  }

  @HostListener('click', ['$event.target']) onClick(btn) {
    btn.innerHTML = 'Loading';
  }

  onCallbackAsync(obj){
    console.log('onCallbackAsync', obj);
    // check if directive matches the callback event
    if (this.asyncLoader === obj.asyncLoader){
      this.elementRef.nativeElement.innerHTML = this.text;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM