尽管主题随后调用,指令订阅仍不会触发 [英] Directive subscription doesn't fire despite the subject calling next

查看:58
本文介绍了尽管主题随后调用,指令订阅仍不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Plunkr: https://plnkr.co/edit/KfPfVSbZm087uIPvFEkM?p=preview

我有一个充当模态组件api的服务,然后有了一个指令,当模态打开时,该指令可用于向任何元素添加类.但是,无论我做什么,指令内的预订都不会触发.

I've got a service which acts as an api for a modal component, and then I got a directive which can be used to add a class to any element when the modal is open. However the subscription inside the directive doesn't fire no matter what I do.

我尝试同时使用SubjectBehaviorSubject,但均无效果.

I've tried using both Subject and BehaviorSubject but none works.

服务:

@Injectable()

export class ModalApiService {

  constructor() {}

  private states = new Subject<any>();

  states$ = this.states.asObservable();

  open(id: string, template?: string): void {
    this.states.next({isOpen: true, id: id, template: template});

    // This runs as expected
    console.log(true);
  }

  close(id: string): void {
    this.states.next({isOpen: false, id: id});
  }
}

指令:

@Directive({
  selector: '[modalState]'
})

export class ModalStateDirective implements OnDestroy, OnInit {

  constructor(private modalApi: ModalApiService) {}

  private modalSubscription: Subscription;

  @HostBinding('class.modal-open')
  isOpen: boolean;

  ngOnInit() {

    this.modalSubscription = this.modalApi.states$.subscribe(
      state => {
        this.isOpen = state.isOpen;

        console.log(this.isOpen)
      }
    );
  }

  ngOnDestroy() {
    this.modalSubscription.unsubscribe();
  }
}

推荐答案

订阅不会触发,因为指令ngOnInit在应用程序的ngOnInit之后引发.因此,next在指令中的预订之前被称为 .这可以通过调用服务打开/关闭方法的简单按钮来证明:

The subscription doesn't fire, because directives ngOnInit is raised after the app's ngOnInit. Thus the next is called before the subscription in the directive. This can be proved with simple button that calls service open/close methods:

toggle() {
  this.modalApi.open('someid');
  this.modalApi.close('someid');
}

演示: https://plnkr.co/edit/MJET0Jw12SLx0BChAiWz?p=preview

如果您真的想从使用该服务打开Dialog开始,那么我建议您使用 ReplaySubject .这应该可以让您在首次订阅之前发出所有声音:

If you really would like to start with open Dialog using the service, then I would suggest you use ReplaySubject. This should give you all emits before the first subscriptions:

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/replaysubject.md

以下是使用ReplaySubject的演示:

Here is a demo using the ReplaySubject:

https://plnkr.co/edit/boHGQhc7atMTOTPLMnO0?p=preview

这篇关于尽管主题随后调用,指令订阅仍不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆