尽管主题接下来调用,但指令订阅不会触发

2024-01-09

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

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

我尝试过同时使用Subject and BehaviorSubject但没有一个有效。

Service:

@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();
  }
}

如果你使用BehaviourSubject,它有效并且会击中subscribe function。但仍然无法确定为什么我们有undefined value of object properties当我能够正确记录对象时。

import 'rxjs/Rx';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

private states = new BehaviorSubject<any>();
states$ = this.states.asObservable();

工作但不工作:https://plnkr.co/edit/YspSd2fKvktPEk6bL2hF?p=preview https://plnkr.co/edit/YspSd2fKvktPEk6bL2hF?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尽管主题接下来调用,但指令订阅不会触发 的相关文章

随机推荐