簡體   English   中英

如何在訂閱中返回 Observable?

[英]How to return an Observable inside a subscription?

編輯:請參閱 Kurt Hamilton 的答案以獲取解決方案。

我正在調用 API 以返回 settings.service.ts 中某些設置的值。 在 settings.component.ts 中,這些需要返回以填寫表單 - 它在 API 調用尚未完成時顯示加載。

它正在使用“(fakeData)的返回”。 但是,我不知道如何返回“realData”。

而不是 console.log(realData) 我想返回它而不是 fakeData。

一些幫助會很好,提前致謝!

下面是代碼的相關部分。

settings.service.ts:

export interface Settings {
  setting1: boolean;
  setting2: string;
}

const fakeData = {
  setting1: true,
  setting2: 'test'
};

@Injectable()
export class SettingsService {
  defaultSettings: DefaultSettings[];

  constructor(private apiService: ApiService) { }

  loadSettings(): Observable<Settings> {
    this.apiService.getDefaultSettings().subscribe( defaultSettings => {
      // defaultSettings is needed for when value1 or value2 is 'null'
      // not implemented yet, but therefore this nested subscription structure
      this.defaultSettings = defaultSettings;

      const value1 = this.apiService.getSpecificSetting('setting1');
      const value2 = this.apiService.getSpecificSetting('setting2');

      forkJoin([value1, value2]).subscribe( result => {
        const realData = {
          setting1: result[0],
          setting2: result[1],
        };

        console.log(realData);
        // return of(settingsFound); not possible here ...
      });
    });

    return of(fakeData);
  }
}

settings.component.ts

settings: Observable<Settings>;

ngOnInit() {
  this.settings = this.settingsService.loadSettings().pipe(
    tap(settings => {
      this.settingsForm.patchValue(settings);
    })
  );
}

使用concatMapswitchMap在另一個 observable 之后運行一個新的 observable (在您的情況下是forkJoin )。

@Injectable()
export class SettingsService {
  defaultSettings: DefaultSettings[];

  constructor(private apiService: ApiService) { }

  loadSettings(): Observable<Settings> {
    return this.apiService.getDefaultSettings().pipe(
      // save default settings
      // this may not be required if you only need default settings for the forkJoin
      tap(defaultSettings => this.defaultSettings = defaultSettings),
      // now run the next observable
      concatMap(defaultSettings => {
        return forkJoin({
          setting1: this.apiService.getSpecificSetting('setting1'),
          setting2: this.apiService.getSpecificSetting('setting2')
        });
      }),
      // now map the result of the forkJoin to the value to want to return
      // map won't be required in this case, 
      // as the arg going into forkJoin matches the desired return structure
      // I left it in for completeness
      map(result => {
        const realData = {
          setting1: result.setting1,
          setting2: result.setting2,
        };

        console.log(realData);

        return realData;
      })
    );
  }
}

精簡版

沒有我的注釋和多余的調用,完成的結果如下所示:

@Injectable()
export class SettingsService {
  constructor(private apiService: ApiService) { }

  loadSettings(): Observable<Settings> {
    return this.apiService.getDefaultSettings().pipe(
      concatMap(defaultSettings => forkJoin({
        setting1: this.apiService.getSpecificSetting('setting1'),
        setting2: this.apiService.getSpecificSetting('setting2')
      }))
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM