Home > front end >  Returning API response from Angular Service to Controller
Returning API response from Angular Service to Controller

Time:11-11

I'm new to Angular and am trying to make an api call and return a response to my form so that I can show a success message.

Here's the function that is living within my service file

upload(files: any): Observable<any> {
    let fileContent = '';
    //set the headers
    const corsHeaders = new HttpHeaders();
    corsHeaders.set('Content-Type', 'text/xml');
    corsHeaders.set('Accept', '*/*');
    corsHeaders.set('Access-Control-Allow-Origin', '*');

    //create form data
    const formData = new FormData();
    //store form name as "file" with file data
    formData.append('UploadedFile', files[0], files[0].name);

    this.http
        .post(this.baseUrl, formData, {
            headers: corsHeaders,
            observe: 'events',
            reportProgress: true,
        })
        .subscribe(
            (ApiResponse) =>
            {                    
                if (ApiResponse.type === HttpEventType.UploadProgress) {
                    console.log('Upload Progress:'   ApiResponse.loaded   '%');
                } else if (ApiResponse.type === HttpEventType.Response) {
                    console.log("Second stage"   ApiResponse);
                } else if (ApiResponse.type === HttpEventType.User)
                {
                    console.log("User Sent a custom message");
                }
                
            }
           
        );
    return new Observable();
}

And here is what I have in my component

onUpload() {
    this.uploadService
        .upload(this.UploadedFiles)
        .subscribe(this.validateSvrResponse(Event));
}

How can I return the results of my service "subscribe" to the this.validateSvrResponse function

CodePudding user response:

You can assign the response returned from the API to a variable and then pass it into the function:

 this.uploadService
        .upload(this.UploadedFiles)
        .subscribe(event=> this.validateSvrResponse(event), error => this.onUploadFailed(error));

and then in your validateSvrResponse function

validateSvrResponse(event){
// Do something
}

onUploadFailed(error){
// Do Something
}

CodePudding user response:

It's better to use Interceptors to set headers for API calls, generally we use Interceptors since in this way we need to write the code just one time, with your approach you need to set manually the headers for each API call.

Have a look to the Angular documentation about the interceptors:

https://angular.io/api/common/http/HttpInterceptor

Regarding your question, you have an error in the code. The issue is that you are subscribing to the http call in the service, but you cannot do that if you want to use the response in the component.

The method in the service needs just to return the response (if you want to write some console logs or do some mapping etc you can use the rxjs pipe operators) and the method in the component need to subscribe to the response observable.

Example:

upload(files: any): Observable<any> {
let fileContent = '';
// It is better to handle this in some Interceptor.
const corsHeaders = new HttpHeaders();
corsHeaders.set('Content-Type', 'text/xml');
corsHeaders.set('Accept', '*/*');
corsHeaders.set('Access-Control-Allow-Origin', '*');

//create form data
const formData = new FormData();
//store form name as "file" with file data
formData.append('UploadedFile', files[0], files[0].name);

return this.http
    .post(this.baseUrl, formData, {
        headers: corsHeaders,
        observe: 'events',
        reportProgress: true,
    });

}

And now, you need to subscribe to this method in component:

// component code
.
.
.
onUpload() {
this.uploadService
    .upload(this.UploadedFiles)
    .subscribe(event => this.validateSvrResponse(event));
}
  • Related