简体   繁体   中英

Angular RXJS need to understand how service works

Can someone please help me to understand this code

Here is a Service https://github1s.com/NG-ZORRO/ng-zorro-antd/blob/HEAD/components/core/config/config.service.ts

and the service method is called from

https://github1s.com/NG-ZORRO/ng-zorro-antd/blob/HEAD/components/alert/alert.component.ts

I need to understand what this method getConfigChangeEventForComponent in constructure() method actually do.

It's always better to put the code in your question:-)

Here's the method:

  getConfigChangeEventForComponent(componentName: NzConfigKey): Observable<void> {
    return this.configUpdated$.pipe(
      filter(n => n === componentName),
      mapTo(undefined)
    );
  }

From looking at getConfigChangeEventForComponent , you can see it is simply filtering the configUpdated$ stream to emit only when the specified component has changed. Then, it simply returns undefined , which implies that the value isn't useful, but only knowing that the config for a specific componentName has changed.

Essentially, this method returns an observable that emits when the config changes for the specified component.

If the method simply returned this.configUpdated$ , then the observable would emit whenever any change was made to any component. However, a couple operators are applied to control when the returned observable emits:

  • filter() is used to only allow emissions where the emitted value equals the provided componentName.
  • mapTo() is used to simply always return undefined to subscribers.

The set() method on the service is what causes configUpdated$ to emit (by calling .next() :

  set<T extends NzConfigKey>(componentName: T, value: NzConfig[T]): void {
    this.config[componentName] = { ...this.config[componentName], ...value };
    this.configUpdated$.next(componentName);
  }

From searching in githubs1 editor, I didn't see any references that called the set() method, but searching github directly showed various places:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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