简体   繁体   中英

Post callback not triggered using rxjs observables

I am trying to debug the response from a post call. The post succeedes and the response is shown inside the response tab in the Chrome developer tools but the promise callback is never triggered.

Any idea why the callback is not triggered?

Here is the subscription:

this.mService.uploadFiles([file.name, new Blob()]).subscribe((response: any) => {
      var myResponse = response;
//Do something with response
    },
      error => {
        var err = `Failed with status = ${error.status}`;
      });

Calling the Rest API:

public uploadFiles(files: any): Observable<any> {

        let formData = new FormData();
        formData.append('file', files[1], files[0]);

        return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {
            observe: 'response'
        }).pipe(map(response => response))
    }

I am actually getting the following error even though the POST succeeds. Probable related to how the service is subscribing.

core.js:4002 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:28)
    at subscribeToResult (subscribeToResult.js:15)
    at CatchSubscriber.error (catchError.js:43)
    at XMLHttpRequest.onLoad (http.js:1707)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:26247)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
    at invokeTask (zone.js:1693)

[UPDATE]

Below is the server side code for the called Azure Function

       [FunctionName("UploadFiles")]
        public async Task<IActionResult> UploadFiles([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequest req, ILogger logger)
        {
            return (ActionResult)new OkObjectResult("Testing");
}

In this case Chrome displays the Testing string in the response tab. The callback is however not triggered.

... but if change the code to only return a OkResult the callback is triggered. So it seems the error appears only if the OkResult contains a payload. Any clue why this is failing?

return (ActionResult)new OkResult();

Give this a try do return response

public uploadFiles(files: any): Observable<any> {

    let formData = new FormData();
    formData.append('file', files[1], files[0]);
    return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {headers : new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})}).pipe(
            map((response: Response) => {
                return response;
            })
            )

}

whenever you do map in service like this do return that value so that mapped value will be return where you subscribing this service

EDIT

Try passing headers since you are passing file object in api

you can try like this

component

this.mService.uploadFiles([file.name, new Blob()]).subscribe((response: any) => {
      var myResponse = response;
// here we are doing other operations like filtering and mapping etc..
      myResponse.pipe(map(result => { console.log(result); }))
    },
      error => {
        var err = `Failed with status = ${error.status}`;
      });

service

public uploadFiles(files: any): Observable<any> {

        let formData = new FormData();
        formData.append('file', files[1], files[0]);

        return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {
            observe: 'response'
        });
    }

Turns out I had to convert the response to json format on the server side (thought this was default json) and escaping the string quotes because the Angular interseptor was expecting json:

 [FunctionName("UploadFiles")]
        public async Task<IActionResult> UploadFiles([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequest req, ILogger logger)
        {
            var jsonResponse = JsonConvert.SerializeObject("Testing");
            return (ActionResult)new OkObjectResult(jsonResponse);
}

and the callback is triggered successfully.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM