简体   繁体   English

如何在订阅中返回 Observable?

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

EDIT: See Kurt Hamilton's answer for the solution.编辑:请参阅 Kurt Hamilton 的答案以获取解决方案。

I'm calling an API to return the values of some settings in settings.service.ts.我正在调用 API 以返回 settings.service.ts 中某些设置的值。 In settings.component.ts these need to be returned to fill a form - it displays loading when the API call isn't finished yet.在 settings.component.ts 中,这些需要返回以填写表单 - 它在 API 调用尚未完成时显示加载。

It's working with the 'return of(fakeData)'.它正在使用“(fakeData)的返回”。 However, I can't figure out how to return the 'realData'.但是,我不知道如何返回“realData”。

Instead of console.log(realData) I want to return that instead of the fakeData.而不是 console.log(realData) 我想返回它而不是 fakeData。

Some help would be nice, thanks in advance!一些帮助会很好,提前致谢!

Beneath are the relevant parts of the code.下面是代码的相关部分。

settings.service.ts: 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.component.ts

settings: Observable<Settings>;

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

Use concatMap or switchMap to run a new observable (in your case a forkJoin ) after another observable.使用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;
      })
    );
  }
}

Condensed version精简版

Without my annotations and the redundant calls, the finished result looks like this:没有我的注释和多余的调用,完成的结果如下所示:

@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