Angular 6 如何将选定的对象从 BehaviourSubject<Object[]> 传递给使用服务的组件?

Angular 6 how to pass selected Object from BehaviourSubject<Object[]> to component using service?

我有一个这样的组件使用 apiService,我按照这种方法使用 BehaviourSubject 来共享来自我的 API 的数据:

settings.component.ts :

export class SettingsComponent implements OnInit {

  data: Observable<Setting[]>;
  public selectedSetting: Setting;

  constructor(private apiService: ApiService,
            private router: Router) { }

  // Load Setting while starting
  ngOnInit() {
    // this.getSettings();
    this.data = this.apiService.fetchData();
  }

  onSelect(setting: Setting): void {
    this.selectedSetting = setting;
  }

  clearSelect(): void {
    this.selectedSetting = null;
  }

  goToSettingDetail(): void {
    this.router.navigate(['settingsDetail']);
  }
}

api.service.ts:

export class ApiService {

  private API_URL = 'someUrl';
  public subject$: BehaviorSubject<Setting[]> = new BehaviorSubject<Setting[]>([]);


  constructor(private httpClient: HttpClient) {
  }

  // use async pipe in html template "*ngFor= let s of settings | async"
  // and just inject ApiService in components constructor
  fetchData() {
    const fetch$: Observable <Setting[]> = this.getSettings().pipe(share());
    fetch$.pipe(
        map(allSettings => this.subject$.next(allSettings))
      )
      .subscribe();
    return fetch$;
  }

  /** GET settings from API*/
  getSettings(): Observable<Setting[]> {
    return this.httpClient.get<Setting[]>(this.API_URL + '/settings')
      .pipe(
        catchError(this.handleError('getSettings', []))
      );
  }
}

所以如果我在这样的 html 文件中有一部分:

<table>
  <tr>
  <th align="left">Id</th>
  </tr>

  <tr *ngFor="let s of data | async">
    <td>{{s.Id}}</td>
    <td>
      <button (click)="onSelect(s); goToSettingsDetail()">ViewSettings</button>
    </td>
  </tr>
</table>

在其他组件中仍然使用 BehaviourSubject 获取选定对象的正确方法是什么?如果我使用附加服务,它从 settingsComponent 中获取选定的对象,它就不再与 BehaviourSubject 相关了,对吗?因此,如果我对其他组件中的选定对象进行更改,没有人会注意到。

你能给我一些提示吗? :)

我会将您选择的设置推送到您的服务中。然后您可以订阅子组件中的选择。

export class ApiService {
  private _selectedSetting$: BehaviorSubject<Setting> = new BehaviorSubject<Setting>(null);
  public selectedSetting$: Observable<Setting> = this._selectedSetting$.asObservable();

  ...

  public setSelectedSetting(s: Setting) {
    this._selectedSetting$.next(s);
  }

  ...
}