how to build single object from 2 http requests in angular, without adding another value

前端 未结 2 1543
谎友^
谎友^ 2020-12-22 10:19

If you look at this question. the problem was really simple, but solutions were more complicated, to address more details I am asking this question.

If you look at

2条回答
  •  半阙折子戏
    2020-12-22 11:06

    If I'm understanding your question correctly, it seems that you are asking about an http request that itself is dependent on another request and that the two requests together need to be combined in some way to create an object that you want to make use of. If I have that correct, then here are some workable examples.

    first, you could just build the object you need in the call itself (i.e. in the component.ts file)

    const id = this.getIdFromRoute(this.route, 'customerId');
    
    let customerWithSource: ICustomer;
    
    this.customerService.getById(id)
        .subscribe((customer) => {
            this.customerSourceService.getById(customer.SourceId)
                .subscribe((source) => {
                    customerWithSource = customer;
                    customerWithSource.CustomerSource = source;
                });
            });
    

    or you could do this in the service, and that way in the component you are just subscribing to a method that already does all the work for you. Great if you are looking for reuse.

        getCustomerWithSource(id: number): Observable {
            return this.getById(id).pipe(
                concatMap((customer) => {
                    return this.customerSourceService
                        .getById(customer.SourceId)
                        .pipe(
                            map((source) => {
                                customer.CustomerSource = source;
                                return customer;
                            }),
                        );
                }),
            );
        }
    

    the way this second one is working is that you are getting the first answer back, then using concatMap to make a second call using the values of the first call, then finally using map to make the final object and returning it.

提交回复
热议问题