-4
var data2 = { data1Id: 0 };

postData(){

this._service1.save(data1).subscribe(res => {
          this.data2.data1Id = res.Data.Id; //res.Data.Id has valid data
     });

     this._service2.save(data2).subscribe(res => {
          console.log(this.data2.data1Id); //"this.data2.data1Id = 0" can't get value from service1
     });
}

how can i get data from the first service or some function take me resolve problem run call service sequence. thank for watching !

2 Answers2

-1
this._service1.save(data1).flatMap(res => {
      this.data2.data1Id = res.Data.Id; //res.Data.Id has valid data
      return this._service2.save(data2);
 }).subscribe(res => {
      console.log(this.data2.data1Id); //"this.data2.data1Id = 0" can't get value from service1
 });

You can use flatMap and return the second observable to chain them. Documentation: http://reactivex.io/documentation/operators/flatmap.html

jvecsei
  • 1,936
  • 2
  • 17
  • 24
-1

Using async/await is perfect for your situation. It will help you to make your code more readable and make abstraction of the async part thanks to the await keyword

aync post(){

    const res1 = await this._service1.save(this.data1).toPromise();
    const res2 = await this._service2.save(res1).toPromise();
    console.log('here is my data 2 ' + res2);

    return 'what you want, can be res1 or res2 or a string';
}

How to call it ?

this.myService.post().then( (whatYouWanted) => {
  console.log(whatYouWanted); // what you want, can be res1 or res2 or a string
});
xrobert35
  • 2,488
  • 1
  • 16
  • 15