【问题标题】:How to subscribe two observable at the same time, with the second observable parameter depending on the result of the first observable?如何同时订阅两个 observable,第二个 observable 参数取决于第一个 observable 的结果?
【发布时间】:2019-12-07 21:30:45
【问题描述】:

我有两个服务,我需要从每个服务中获取一个 observable。我在互联网上搜索并找到了一个解决方案,在这里:Is it good way to call subscribe inside subscribe? 但这对我不起作用。 这两个 observable 单独调用时效果很好。

export class EditVarianteComponent implements OnInit {

  public currentVariante: Variante;
  public url: string;
  public value$: any;

  constructor(
    private router: Router, 
    private activatedRoute: ActivatedRoute, 
    private varService: VarianteService, 
    private famService: FamillesService
  ) {}

  ngOnInit() {
    this.url = atob(this.activatedRoute.snapshot.params.id);
    //Here, I get the resource, and I want the result of this resource to be the parameter of my second observable
    this.varService.getResource(this.url)
      .pipe(
          flatMap((res1) => this.famService.getFamilleById(res1.id_famille))
      )
      .subscribe((res3) => {
          console.log(res3);
      });
  }

【问题讨论】:

  • 控制台有错误吗?
  • 是的,res1.id_famille 未定义。
  • 如果您控制台日志 res1 是否返回任何内容?
  • “res1.id_famille 未定义”或“无法读取未定义的属性 'id_famille'”? getResource 的作用如何?

标签: angular


【解决方案1】:

你可以这样试试:

import { map } from "rxjs/operators";

this.url = atob(this.activatedRoute.snapshot.params.id);


 this.varService.getResource(this.url).pipe(
  mergeMap(res1 => this.famService.getFamilleById(res1.id_famille))
);

【讨论】:

  • 我已经尝试了解决方案,但在第二行中我得到了错误:属性映射不存在于类型 Observable
  • 你导入 rxjs 了吗? import 'rxjs/Rx'; 这往往就是出现此错误的原因。
  • 是的,我已经导入了它,但我得到了错误:找不到模块:错误:无法解析 'rxjs/Rx' .. 自从 1 周以来我就被阻止了
  • 你需要import { map } from "rxjs/operators"
  • 为您提供时间和答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
相关资源
最近更新 更多