0

Trying to http post items of an array one after another in sequence. Knowing should use RxJS flatMap but couldn't make it work. Basically I need something like this:

item is an element of an array named items, want to go through the array and send each item.

    this.http.post(url, item)
        .subscribe(
          (response) => {
            // call the same http.post again to send the next item
          },
          (error) => {
            this.app.error(error.json() as Error); // exit
          }         
        )

Thanks for the help.

brewphone
  • 1,316
  • 4
  • 24
  • 32

3 Answers3

2

maybe try concat

Rx.Observable.concat(...items.map(item => this.http.post(url, item)).subscribe(res => doSmthWithResponse());
kit
  • 4,890
  • 3
  • 24
  • 23
  • Thank you for the response. "ng build" complains "Property 'subscribe' does not exist on type 'Observable[]'." on following code: Observable.concat(items.map( (item:Item) => this.http.post(url, item)) .subscribe(response => this.doSomething() ) ); – brewphone May 02 '17 at 01:55
  • you forgot to add "..." (spread operator) in front of items.map. try Observable.concat(...items.map( (item:Item) => this.http.post(url, item)) .subscribe(response => this.doSomething() ) ); – kit May 02 '17 at 07:20
  • Really didn't know spread operator, thank you. But got exactly the same error with this code: Observable.concat(...items.map( (item:Item) => this.http.post(url, item)).subscribe(response => this.doSomething() ) ); Should the issue be in my import: import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/concat'; Any other import? Thank you very much. – brewphone May 02 '17 at 13:51
  • you miss one closing parentheses before subscribe, try this: Observable.concat(...items.map( (item:Item) => this.http.post(url, item))).subscribe(response => this.doSomething() ) ); – kit May 02 '17 at 17:49
0
  this.http.post(url, item).map(res => res.json())
            switchMap(this.http.post(url1, item).map(res => res.json()))    
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
0

You can try using from and flatmap

Observable.from(items)
    .flatMap(item => this.http.post(url, item))
    .subscribe({
        res => console.log("your response"),
        error => console.log("your error"),
        () => doSomethingAtEnd()
    });
Kowsalya
  • 1,378
  • 16
  • 25