Reputation: 1683
I have 3 functions and one button. I want to press the button and call 3 function
not at the same time, but one after another, so each function waits till another (previous function) is completed
I have a onPost,
onGet
and navigate
function
What I would like to do ist to call a function allTogether
allTogether() {
this.onPost();
this.onGet();
this.navigate();
}
Here is my onPost
Method, where I send data of current client to backend
onPost () {
const messageForDb = (JSON.stringify(this.model));
localStorage.setItem('userKey', messageForDb);
this._httpService.postJSON(this.model)
.subscribe(
data => this.postData = JSON.stringify(data),
error => alert(error),
);
}
Here is my onGet()
and here I get information about my client, so I can use it later in third function navigation()
onGet() {
this._httpService.getCurrentState(this.model.user_email, this.model.client)
.subscribe(
// data => this.getData = JSON.stringify(data),
data => this.getData = data,
error => alert(error),
);
}
navigation () {
let part = json.message.part;
let num = json.message.number;
this.router.navigate(['part'], {queryParams: {'number': 'num'}});
}
I tried with subscribe, but failed...so how cloud I implements the function allTogether()
else ? I tested all functions and they work separately, but all together..
Upvotes: 0
Views: 56
Reputation: 1615
You can use the Observable.forkJoin
operator to make the third function wait for the results of the first 2. I see the data between them is not dependent on each other. You also have to modify onPost
and onGet
so they return observables
.
onPost () {
const messageForDb = (JSON.stringify(this.model));
localStorage.setItem('userKey', messageForDb);
return this._httpService.postJSON(this.model);
}
onGet() {
return this._httpService.getCurrentState(this.model.user_email, this.model.client);
}
Observable.forkJoin([this.onPost(), this.onGet()])
.subscribe((resultArray) => {
[postResult, getResult] = resultArray;
this.postData = JSON.stringify(postResult);
this.getData = getResult;
this.navigation();
});
Upvotes: 2
Reputation: 3062
You just need to call the next method from the part of the subscribe function that assigns the data.
onPost () {
const messageForDb = (JSON.stringify(this.model));
localStorage.setItem('userKey', messageForDb);
this._httpService.postJSON(this.model)
.subscribe(
data => { this.postData = JSON.stringify(data); this.onGet();},
error => alert(error),
);
}
onGet() {
this._httpService.getCurrentState(this.model.user_email,
this.model.client)
.subscribe(
// data => { this.getData = JSON.stringify(data); this.navigate(); },
data => { this.getData = data; this.navigate(); },
error => alert(error),
);
}
Upvotes: 1