如何使用其他 Observable 中的返回值返回一个 Observable 和其他 Observable 的数据

发布于 2025-01-16 21:05:06 字数 1865 浏览 0 评论 0原文

我有一个项目,我想返回 Hero 对象的 Observable 。 我的英雄有多个 id 属性来从其他 Observables 获取数据作为 SkillRarity。我的 Observables 来自 AngularFire 库。这是我现在拥有的英雄类:

export class Hero extends Serializable {
  id?: string;
  name?: string;
  description?: string;
  idRarity?: string;
  rarity?: Rarity;
  stats: Stats;
  idSkill1?: string;
  idSkill2?: string;
  skill1?: Skill;
  skill2?: Skill;
  visual?: string;
  dateAdded?: Date;

  constructor() {
    super();
    this.stats = {};
    this.visual = "assets/images/placeholder.jpg";
  }
  ...

}

  // functions from the HeroService
  getHeroes(): Observable<Hero[]> {
    return this.db.collection<JsonArray>(HeroService.url)
      .valueChanges()
      .pipe(
        map(documents => {
          return documents.map(data=> {
            return this.getHeroFromData(data);
          });
        })
      );
  }

  getHero(id: string): Observable<Hero | undefined> {
    // Returns hero|undefined observable
    return this.getHeroDocument(id).valueChanges()
      .pipe(
        map(data => {
          return data ? this.getHeroFromData(data) : undefined
        })
      );
  }

  getHeroFromData(data:JsonArray) {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      this.skillService.getSkill(hero.idSkill1).subscribe(skill => hero.skill1 = skill);
      this.skillService.getSkill(hero.idSkill2).subscribe(skill => hero.skill2 = skill);
      this.rarityService.getRarity(hero.idRarity).subscribe(rarity => hero.rarity = rarity);
    }
    return hero;
  }

我面临的问题是,当我的英雄返回时,我的稀有度和技能属性的数据尚未设置。

有没有办法在返回英雄对象之前等待从其他 Observables 接收到所有值?

I have a project in which I want to return an Observable of Hero object.
My heroes have multiple id properties to fetch data from other Observables as a Skill or a Rarity. My Observables come from the AngularFire library. Here is my Hero class what I have right now:

export class Hero extends Serializable {
  id?: string;
  name?: string;
  description?: string;
  idRarity?: string;
  rarity?: Rarity;
  stats: Stats;
  idSkill1?: string;
  idSkill2?: string;
  skill1?: Skill;
  skill2?: Skill;
  visual?: string;
  dateAdded?: Date;

  constructor() {
    super();
    this.stats = {};
    this.visual = "assets/images/placeholder.jpg";
  }
  ...

}

  // functions from the HeroService
  getHeroes(): Observable<Hero[]> {
    return this.db.collection<JsonArray>(HeroService.url)
      .valueChanges()
      .pipe(
        map(documents => {
          return documents.map(data=> {
            return this.getHeroFromData(data);
          });
        })
      );
  }

  getHero(id: string): Observable<Hero | undefined> {
    // Returns hero|undefined observable
    return this.getHeroDocument(id).valueChanges()
      .pipe(
        map(data => {
          return data ? this.getHeroFromData(data) : undefined
        })
      );
  }

  getHeroFromData(data:JsonArray) {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      this.skillService.getSkill(hero.idSkill1).subscribe(skill => hero.skill1 = skill);
      this.skillService.getSkill(hero.idSkill2).subscribe(skill => hero.skill2 = skill);
      this.rarityService.getRarity(hero.idRarity).subscribe(rarity => hero.rarity = rarity);
    }
    return hero;
  }

The issue I'm facing is that when my hero is returned, the data for my properties of rarity and skills are not set yet.

Is there a way to wait for all values to be received from the other Observables before returning the hero object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

离去的眼神 2025-01-23 21:05:06

RxJs 6.5+

forkJoin 将完全填充您的要求在这里。

还了解 mergeMap

  // functions from the HeroService
  getHero(id: string): Observable<Hero | undefined> {
    // Returns hero|undefined observable
    return this.getHeroDocument(id)
      .valueChanges()
      .pipe(
        mergeMap((data) => {
          return data ? this.getHeroFromData(data) : of(undefined);
        })
      );
  }

  getHeroFromData(data: JsonArray): Observable<Hero> {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      forkJoin({
        skill1: this.skillService.getSkill(hero.idSkill1),
        skill2: this.skillService.getSkil1(hero.idSkill2),
        rarity: this.rarityService.getRarity(hero.idRarity),
      }).pipe(
        map((res) => {
          hero.skill1 = res.skill1;
          hero.skill2 = res.skill2;
          hero.rarity = res.rarity;

          return hero;
        })
      );
    }
  }

RxJs 6.5+

forkJoin will full fill your requirement here.

know about mergeMap also

  // functions from the HeroService
  getHero(id: string): Observable<Hero | undefined> {
    // Returns hero|undefined observable
    return this.getHeroDocument(id)
      .valueChanges()
      .pipe(
        mergeMap((data) => {
          return data ? this.getHeroFromData(data) : of(undefined);
        })
      );
  }

  getHeroFromData(data: JsonArray): Observable<Hero> {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      forkJoin({
        skill1: this.skillService.getSkill(hero.idSkill1),
        skill2: this.skillService.getSkil1(hero.idSkill2),
        rarity: this.rarityService.getRarity(hero.idRarity),
      }).pipe(
        map((res) => {
          hero.skill1 = res.skill1;
          hero.skill2 = res.skill2;
          hero.rarity = res.rarity;

          return hero;
        })
      );
    }
  }
浮光之海 2025-01-23 21:05:06

如果你的英雄和技能被加载一次,你应该考虑使用 Promise 而不是 Observable。如果您无法将其更改为核心,则可以使用 .toPromise() 将可观察量转换为 Promise。然后你可以使用Promise.all()。

getHeroFromData(data:JsonArray): Promise<Hero> {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      const promise 1 = this.skillService.getSkill(hero.idSkill1).toPromise().then(skill => hero.skill1 = skill);
      const promise2 = this.skillService.getSkill(hero.idSkill2).subscribe(skill => hero.skill2 = skill);
      const promise3 = this.rarityService.getRarity(hero.idRarity).subscribe(rarity => hero.rarity = rarity);
      return Promise.all([promise1, promise2, promise3]).then(() => hero);
    } else {
      return Promise.resolve(hero);
    }        
  }

那么调用该方法时必须使用then。因为 Hero 是以异步方式构建的,所以您必须以异步方式处理返回。使用 then()。

If your hero and skills are loaded once, you should consider using promises instead of observables. If you cannot change it to the core, you can convert an observable to a promise with .toPromise(). Then you can use Promise.all().

getHeroFromData(data:JsonArray): Promise<Hero> {
    let hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      const promise 1 = this.skillService.getSkill(hero.idSkill1).toPromise().then(skill => hero.skill1 = skill);
      const promise2 = this.skillService.getSkill(hero.idSkill2).subscribe(skill => hero.skill2 = skill);
      const promise3 = this.rarityService.getRarity(hero.idRarity).subscribe(rarity => hero.rarity = rarity);
      return Promise.all([promise1, promise2, promise3]).then(() => hero);
    } else {
      return Promise.resolve(hero);
    }        
  }

Then you must use then when calling this method. Because hero is build in a async way, you must treat the return in a async way. Use then().

琴流音 2025-01-23 21:05:06

经过几次尝试,我设法使用 zip 运算符来实现

它这就是我最终得到的。

  getHeroes(): Observable<Hero[]> {
    return this.db.collection<JsonArray>(HeroService.url)
      .valueChanges()
      .pipe(
        mergeMap((docs) => {
          return zip(docs.map((doc) => { return this.getHeroFromData(doc) }))
        })
      );
  }


  getHero(id: string): Observable<Hero | undefined> {
    return this.getHeroDocument(id).valueChanges()
      .pipe(
        mergeMap(data => { return data ? this.getHeroFromData(data) : of(undefined) })
      );
  }

  private getHeroFromData(data: JsonArray): Observable<Hero> {
    const hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      return zip(
        this.skillService.getSkill(hero.idSkill1),
        this.skillService.getSkill(hero.idSkill2),
        this.rarityService.getRarity(hero.idRarity)
      ).pipe(
        map(res => {
          console.log(res);
          hero.skill1 = res[0];
          hero.skill2 = res[1];
          hero.rarity = res[2]
          return hero;
        })
      )
    }
    return of(hero);
  }

After a few attempts, I manage to achieve it using zip operator

Here is what I have in the end.

  getHeroes(): Observable<Hero[]> {
    return this.db.collection<JsonArray>(HeroService.url)
      .valueChanges()
      .pipe(
        mergeMap((docs) => {
          return zip(docs.map((doc) => { return this.getHeroFromData(doc) }))
        })
      );
  }


  getHero(id: string): Observable<Hero | undefined> {
    return this.getHeroDocument(id).valueChanges()
      .pipe(
        mergeMap(data => { return data ? this.getHeroFromData(data) : of(undefined) })
      );
  }

  private getHeroFromData(data: JsonArray): Observable<Hero> {
    const hero = new Hero().fromJSON(data);
    if (hero.idSkill1 && hero.idSkill2 && hero.idRarity) {
      return zip(
        this.skillService.getSkill(hero.idSkill1),
        this.skillService.getSkill(hero.idSkill2),
        this.rarityService.getRarity(hero.idRarity)
      ).pipe(
        map(res => {
          console.log(res);
          hero.skill1 = res[0];
          hero.skill2 = res[1];
          hero.rarity = res[2]
          return hero;
        })
      )
    }
    return of(hero);
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文