0

i have a quick question regarding Angular 4 and the Observable. In my program i have a Component, which creates a list of "things" that should be send to an api. Secondly, i have a service, which gets an element ("thing" --> one!), sends it to the api and returns a Observable. Here´s the code: Component:

saveTimers() {
    // gehe alle selektierten Timer durch und lege Sie an
    let timerSuccess = [];
    let timerFailed = [];
    let timers = [];
    for (let epgEntry of this.searchResult) {
        if (epgEntry.checked) {
            let timer = new Timer;
            // magic
            this.timerService.saveTimer(timer).
                subscribe(
                data => {
                    console.log(data);
                    if (data) {
                        timerSuccess.push(timer);
                    } else {
                        timerFailed.push(timer);
                    }
                },
                error => { this.variables.setFailure(error); }
                );
        }
        }
//both empty, because api didn´t return yet
        console.log(timerSuccess);
        console.log(timerFailed);
        if (timerSuccess.length > 0) {
            this.variables.setSuccess('Timer erfolgreich angelegt');
        }
        if (timerFailed.length > 0) {
            this.variables.setFailure('Timer konnte(n) nicht angelegt werden');
        }
    }

Service:

saveTimer(timer: Timer): Observable<boolean> {
// magic --> returns an observable
}

Now the question: how can i use Observable.forkJoin() (in the component) to do ALL api calls at one time (btw wait for all api calls)?

Thanks so much!

1 Answer 1

1

Something like this:

Observable.forkJoin(Observable.of(YOUR_ARRAY), saveTimer(timer: Timer))
    .switchMap(joined => Observable.forkjoin(http.post(joined[0]), http.post(joined[1])))
    .subscribe();

In the first forkjoin you combine your value that you want to send. In the second you combine the results of the two api calls.

Sign up to request clarification or add additional context in comments.

1 Comment

ok, thanks! But where i have to put this...? In the component instead of the call to the service? but then 'saveTimer(timer: Timer) won´t work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.