I have spring boot service which provides csv file as response.
How do we call this service from angular 5 typescript.
download of a file should happen depends on some input parameters so I will have post call with user clicks the export button.
below is the rest code in controller.
@Controller
public class MyController {
@RequestMapping(value = "/downLoadDataQueryCsv", method = RequestMethod.GET)
public ResponseEntity<Object> downLoadDataQueryCsv(Model model) throws IOException {
FileWriter fileWriter = null;
try {
DataQueryRequestParams dataQueryRequestParams = new DataQueryRequestParams();
dataQueryRequestParams.setMbuCategory("UKY");
// Result table.
List<OrderIdFinalRank> rankList = // call api to get data.
// construct headers
List<String> csvHeaders = constructDataQueryHeaders();
StringBuilder fileContent = new StringBuilder(String.join(",", csvHeaders));
fileContent.append("
");
// construct file content from response
for(OrderIdFinalRank finalRank : rankList) {
fileContent.append(StringUtils.join(constructDataQueryRow(finalRank), ",")).append("
");
}
String fileName = new String("DataQueryTab.csv");
fileWriter = new FileWriter(fileName);
fileWriter.write(fileContent.toString());
fileWriter.flush();
File file = new File(fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename="%s"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length())
.contentType(MediaType.parseMediaType("application/txt")).body(resource);
return responseEntity;
} catch (Exception e) {
System.out.println("Exception: " +e);
return new ResponseEntity<>("Error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
if(null != fileWriter) {
fileWriter.close();
}
}
}
}
Now I need to call this from UI when I click export button, what have written is below.
I have read file saver and added below code, but its not working. kindly help me.
@Injectable()
export class ApiService {
onExport(dataQueryRequestParams: any) {
const dataQueryURL = API_URL + '/downLoadDataQueryCsv';
const body = JSON.stringify(dataQueryRequestParams);
this._http.get(dataQueryURL).subscribe(res => {
saveAs(res, 'data.csv');
});
}
}
Note: When I ran rest URL from browser the file is downloaded, but the same needs to happen when I click export button.
Am new to UI technologies.
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…