【问题标题】:Service bound / created to / by a component (observer pattern)服务绑定/创建到/由组件(观察者模式)
【发布时间】:2016-02-23 06:42:32
【问题描述】:

有没有办法创建一个“绑定”到组件的服务,或者更好地说:可以由组件创建的服务?

我有以下情况:

我页面上的某个地方是一个搜索框。页面上的所有组件都应该能够订阅此搜索框的更改,并在更改时收到通知。

我想到的唯一方法是使用服务。 但是我不知道如何从我的组件创建服务(我还想过在提供服务时使用factorysetValue 等,但这也对我没有帮助(?))。

正如您在我的代码中看到的,我添加了一种解决方法,如果多个组件试图成为服务的“提供者”,我会抛出错误。但是,我认为这是一个丑陋的 hack,如果可能的话,我想以不同的方式来做。

我的搜索组件:

@Component({
    selector: 'my-search-box',
    template: `<input type="text" #box (keyup)="onKey(box.value)" />`,
    providers: [SearchService]
})
export class SearchBoxComponent implements OnInit {

    private _updateSearchFunc : (searchValue: string) => void;

    constructor(private _searchService: SearchService) {
    }

    ngOnInit() {
        this._updateSearchFunc = this._searchService.registerAsProvider();

        // if another component would also try this, it would result in an exception, so it's kind of the "first come first serve" principle..
        //this._updateSearchFunc = this._searchService.registerAsProvider();

        var activeTab = this._cookieManager.get(Constants.CookieNameActiveTab);
        if (activeTab) {
            this._router.navigateByUrl("/" + activeTab);
        }
    }

    onKey(value:string) {
       this._updateSearchFunc(value);
    }
}

我的服务:

export class SearchService {
  private _searchValueChangeEventEmitter: EventEmitter<string> = new EventEmitter();

  private _hasProvider = false;

  constructor() {}

  registerAsProvider() : (searchValue: string) => void {
      if (this._hasProvider) {
          throw new Error("There's already a provider registered!");
      }

      this._hasProvider = true;
      return this.emit;
  }

  subscribe(callback : (searchValue: string) => void) {
    return this._searchValueChangeEventEmitter.subscribe(callback);
  }

  // correct this context
  private emit = (searchValue: string) : void => {
    this._searchValueChangeEventEmitter.emit(searchValue);
  }
}

【问题讨论】:

  • 也许你可以使用valueChanges observable,form controls 有?
  • 嗯,我不明白这有什么帮助..
  • 您的示例看起来太复杂了,不适合您尝试做的事情(;如果您创建一个搜索表单,您可以更轻松地订阅输入控件更改...
  • 但是整个应用程序中的所有组件都能收到更改通知吗?有代码示例吗?

标签: angular observer-pattern eventemitter


【解决方案1】:

我认为这种方法没有问题,也不是更好的方法。

您必须在bootstrap(AppComponent, [ ..., SearchService])AppComponentproviders: [SeachService] 中注册服务,否则它不适用于整个应用程序。

【讨论】:

  • “悲伤”听到它......但无论如何还是谢谢。是的,关于我知道的注册..:)
猜你喜欢
  • 2023-04-10
  • 2018-11-11
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多