Angular5 如何优先考虑ngOnInit中的订阅,而不是随机执行?

Angular5 如何优先考虑ngOnInit中的订阅,而不是随机执行?,angular5,Angular5,在我的ngOnInit()方法中有多个订阅 既然我需要一个在另一个中的响应,我如何按顺序执行它们。 因此,如果先执行另一个,我将对该个进行未定义 我需要响应。你可以像这样嵌套观测值 this.customerService.getById(id) .subscribe((customer) => { this.customerSourceService.getById(customer.SourceId) .subscribe((source

在我的ngOnInit()方法中有多个订阅
既然我需要一个在另一个中的响应,我如何按顺序执行它们。

因此,如果先执行另一个,我将对该个进行未定义

我需要响应。

你可以像这样嵌套观测值

this.customerService.getById(id)
    .subscribe((customer) => {
        this.customerSourceService.getById(customer.SourceId)
            .subscribe((source) => {
                customerWithSource = customer;
                customerWithSource.CustomerSource = source;
            });
        });
这允许您在第二个订阅中使用第一个订阅的答案

您还可以使用像concatMap这样的操作符,它允许您将多个观测值链接到一个订阅中,并允许您在下一个订阅中使用每个观测值,确保它们以特定顺序运行

下面是我对一个类似问题的回答,其中有更多的细节