Link to home
Start Free TrialLog in
Avatar of Karthey Sundarem
Karthey Sundarem

asked on

promise call and component method to webapi that returns csv file

Hi,
I need to call the webapi that returns csv file.  Currently, I wrote an observable.  Something is wrong with the promise call and component code .WebAPI method is working fine.

Component:
**********
 downloadfile() {
        this.isLoading = true;
        this.customerMonitoringService.getMyFileFromBackend(this.productionDataUrl).subscribe(
            res => {
            this.isLoading = false;
                res;
            },
            (error: any) => Observable.throw(error || 'Server error')
        );
    }


cust-monitoring.service.ts
****************************

  getMyFileFromBackend(productionURL: string): Observable<any> {
       
        return this.http.get("`"+productionURL+"`")
            .map(res => res.text())
                .catch((error: any) => Observable.throw(error || 'Server error'));
    }


Web API call
**************

        [HttpGet]
        [HttpPost]
        public async Task<IHttpActionResult> Index(string systemName)
        {
              var negotiator = Configuration.Services.GetContentNegotiator();
           
            var mediaTypeFormatterCollection = new MediaTypeFormatterCollection();
            mediaTypeFormatterCollection.Clear();
            mediaTypeFormatterCollection.Add(new ProductionPeriodFormatter());
            mediaTypeFormatterCollection.Add(new JsonMediaTypeFormatter());

            var result = negotiator.Negotiate(typeof(ProductionPeriod), Request, mediaTypeFormatterCollection);
            if (result == null)
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotAcceptable));

            var production = await Production(systemName);
            var content = new ObjectContent<ProductionPeriod>(
                production,
                result.Formatter,
                result.MediaType.MediaType
            );
            if (result.Formatter is JsonMediaTypeFormatter)
            {
                ((JsonMediaTypeFormatter) result.Formatter).SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
                content.Value = new ProductionPeriod(production.Start, production.End, production.TimeZone, interval.Value,
                    NormalizedIntervals(production, interval.Value));
            }
            else
            {
                try
                {
                    WebRequest.DefaultWebProxy = null;

                    content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "production.csv"
                    };
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = ex.Message.ToString();
                }
            }

            var response = new HttpResponseMessage()
            {
                Content = content
            };
          
            return ResponseMessage(response);
        }
Thanks

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Can you provide a bit more information about what is not working / or what it is you want to achieve - it is not clear from your question

There are several moving parts here

1. The Angular code that initiates the call
2. The backend that returns the file

Firstly - is the service working correctly - is it returning a file?
Secondly, what part of the code is not working - how is it not working - are there errors / unexpected returned data / no data

If you can give us a starting point it will be easier to solve your problem.
Avatar of Karthey Sundarem
Karthey Sundarem

ASKER

The backend resturns the file. I use call it with <a  href=url.  It works fine.
Now I need to add the spinner, since app takes too much time to return data depends on the request(30 sec - 3 min.)
I added the spinner now.  
But for some-reason, the way I call the csv file, the angular service layer call gets "data <unavailable>".

 downloadfile() {
        this.customerMonitoringService.getMyFileFromBackend(this.productionDataUrl).subscribe(data =>
            this.downloadFileFromAPI(data))   }

    downloadFileFromAPI(data: Response) {
        var blob = new Blob([data], { type: 'text/csv' });
        var url = window.URL.createObjectURL(blob);
        if (navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, 'Production.csv');
        } else {
            let a = document.createElement('a');
            a.href = url;
            a.download = 'Production.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        window.URL.revokeObjectURL(url);
        //var blob = new Blob([data], { type: 'text/csv' });
        //var url = window.URL.createObjectURL(blob);
        //window.open(url);
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial