I'm currently doing a POST method and routing my application with some params but the problem seems to be that application routes before the POST method is completed and comes bk with a response.
my function:
let responseBody;
let postUploads = function() {
return this.http.post(url, uploadFile).pipe((response: any) => this.responseBody = response);
}
postUploads().subscribe(() => this.router(['/inbox], { queryParams: {file: responseBody} }));
the issue that is happening is that it goes to the route before the "responseBody" is returned as a response from the POST
how do i make it wait for the response to come back before i route the user?
You have a couple of issues here.
let responseBody;
let postUploads = function() {
return this.http.post(url, uploadFile).pipe((response: any) => this.responseBody = response);
}
In this code, because you are declaring a function using function() { }
syntax, this
will reference the function itself. this.http
will be undefined.
Also, it looks like you are attempting to set the local variable responseBody
with the expression this.responseBody = response
.
It is also an incorrect use of pipe
. Pipe accepts RxJS operators, such as map
, tap
, etc. It doesn't accept a callback like this.
this.router(['/inbox], { queryParams: {file: responseBody} })
In this code you are not calling the router in a correct way. I suspect you mean this.router.navigate(['/inbox], { queryParams: {file: responseBody} })
;
Your code can be simplified to the following:
this.http.post(url, uploadFile).subscribe((response: any) => {
this.router.navigate(['/inbox'], { queryParams: {file: response } });
});
This subscribes to the observable and performs navigation when the response is received. I don't know what data type response
is, but if it's some kind of blob, you probably don't want to put it in the url.
You are referencing the wrong responseBody
.
Try this instead:
this.http.post(url, uploadFile)
.subscribe(responseBody => this.router(['/inbox'], { queryParams: { file: responseBody } }))
The idea is to let the output of observable (eg http.post()
) flow through the observable chain.
I think local variable responseBody is unnecessary here. You can directly get the reference of responseBody inside the subscribe method. I have removed the unnecessary code, please check and let me know if it works.
let postUploads = function() {
return this.http.post(url, uploadFile);
}
postUploads().subscribe((responseBody) => this.router(['/inbox], { queryParams: {file: responseBody} }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.