getProductbyFilter(filter: filterDataModel): Observable<any> {
this.stringtoArrayService.convertStringtoArray(some string input).subscribe(productUserResponse => {
if (productUserResponse) {
this.userProfileProduct = productUserResponse;
this.newParams = this.userProfileProduct[0].Function_Network;
if (this.newParams != null) {
this.updatedStr = this.newParams.replace('&', '__', this.newParams);
} else {
this.updatedStr = this.userProfileProduct[0].Function_Network;
}
}
});
return this.http.post(url this.updatedStr, filter, httpOptions);}
I have already visited these links they said to use method inside subscribe. I want to access this.updatedStr but it's returning undefined. I can't write return inside subscribe also. Can anyone please help?
CodePudding user response:
Try this.. I have not tested it though.
setUpdatedStr(productUserResponse){
if (productUserResponse) {
this.userProfileProduct = productUserResponse;
this.newParams = this.userProfileProduct[0].Function_Network;
if (this.newParams != null) {
this.updatedStr = this.newParams.replace('&', '__', this.newParams);
} else {
this.updatedStr = this.userProfileProduct[0].Function_Network;
}
}
}
getProductbyFilter(filter: filterDataModel): Observable<any> {
return this.stringtoArrayService.convertStringtoArray(some string input).pipe(
tap(productUserResponse => this.setUpdatedStr(productUserResponse)),
switchMap(_=>callAfterSetUpdaterStr(filter))
);
callAfterSetUpdaterStr(filter: filterDataModel): Observable<any>{
// set httpOptions and url
return this.http.post(url this.updatedStr, filter, httpOptions);
}
CodePudding user response:
That is how JavaScript works
getProductbyFilter() {
yourSubcriptionThatSetsUpdatedStr();
return yourStatementThatReturnHttpCallObs();
}
yourSubcriptionThatSetsUpdatedStr
is independent of yourStatementThatReturnHttpCallObs
. So that javascript will finish yourStatementThatReturnHttpCallObs
before yourSubcriptionThatSetsUpdatedStr
which means this.updatedStr
is returned even before it gets assigned a value from yourSubcriptionThatSetsUpdatedStr
; that makes this.updatedStr
an undefined.
use Promise or Async/Await to make yourStatementThatReturnHttpCallObs
wait for yourSubcriptionThatSetsUpdatedStr
to finish.
so that you can return from initial method;