Angular: prevent auto recompile when there is a change in assets folder
Asked Answered
M

2

7

I'm trying to download a file generated from spring boot in the assets of the angular project. When I call the spring API from angular services, angular CLI recompiles the project after the creation of the file in assets angular folder, and then it reloads the page before getting the response from spring boot API.

I tried to call the spring boot API from angular in many ways:

  • calling the api in the ngOnInit() of my component
  • calling the api in the constructor of my component
  • calling the api in a separate function
  • using async await in the download function

I don't know ho to proceed

spring boot

 @GetMapping(path = "/downloads/{fileId}", produces = "application/json")
    @ResponseBody
    public ResponseEntity<String> download(@PathVariable String fileId){
        Gson gson = createGson();

        List<com.bioimis.blp.entity.File> fileById;

        try {
            fileById = fileRepository.findFileById(fileId);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

        if (fileById.isEmpty()) {
            logger.error(fileId + " not found");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        if(fileById.get(0).getDeletionDate() != null) {

            List<String> phrases = new ArrayList<>();

            try {
                phrases = translationRepository.getAllTranslationsByFileId(fileById.get(0).getId());
            } catch (Exception e) {
                logger.error(e.getMessage());
                return ResponseEntity.status(HttpStatus.OK).body(null);
            }

            String file = "";

            for (int i = 0; i < phrases.size(); i++) {
                file = file.concat(phrases.get(i));
            }
            file = file.concat("\0");

            /*Suppongo che prima dell'estensione gli ultimi 5 caratteri del file sono in formato 'languageCode_countryCode'*/
            String nameFile = fileById.get(0).getPath().split("/")[fileById.get(0).getPath().split("/").length - 1];

            Language language;
            try {
                language = languageRepository.findLanguageById(fileById.get(0).getLanguageId()).get(0);
            } catch (Exception e) {
                logger.error(e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
            }

            int i = StringUtils.lastIndexOf(nameFile, '.');
            String ext = StringUtils.substringAfter(nameFile, ".");

            nameFile = nameFile.substring(0, i - 5) + language.getLanguageCode() + "_" + language.getCountryCode() + "." + ext;

            Path path = Paths.get(pathDownload + "/" + nameFile);

            try {
-----------------------------------------------------------------------------
                Files.write(path, file.getBytes());
------------>after this instruction, angular reloads the page<---------------
-----------------------------------------------------------------------------
            } catch (IOException e) {
                logger.error(e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
            }

            return ResponseEntity.status(HttpStatus.OK).body(gson.toJson(path.toString()));
        }

        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

Angular Component

 downloadFile(fileId: string) {
    let link: string;

    this.http.downloadFile(fileId).subscribe(
      data => {
        link = data;
      }
    );

    console.log(link);
    return link;
  }

Angular Service

downloadFile(fileId: string) {
    const myheader = new HttpHeaders().set('Authorization', this.token);
    return this.http.get<string>(this.url.concat('files/downloads/' + fileId), { headers: myheader });
  }

I just expect to get the response from spring boot api without reloading the angular component.

(In postman it works as it has to be)

Milden answered 13/9, 2019 at 7:44 Comment(0)
M
0

There are 2 reasons why this doesn't function at all:

  • Binding the function in HTML component template makes infinite loop, that's a bad practice.
  • Creating a file in assets where in Angular that's static folder, so every time that folder, or external folders linked in assets in angular.json, is updated with a new file, it reloads the component

I modified my download function that returns all the text of the file through the response and then I created a blob file (https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts) where it will be downloaded when the user click the download button.

Milden answered 14/9, 2019 at 7:52 Comment(0)
F
1

Start the angular application as (instead of ng serve)

ng serve --live-reload false

--liveReload=true|false Whether to reload the page on change, using live-reload.

Default: true

Angular Commands

Alternatives

  • ng serve --no-live-reload

  • ng serve --live-reload=false

  • create command in package.json as "ng noreload" : "ng serve --live-reload=false"

Fortunna answered 14/9, 2019 at 6:59 Comment(2)
Good answer, but I still prefer to keep live reloadMilden
It doesn't solve the purpose, it doesn't showing the updated code changes in browser, it's just preserving the code changes nothing else. Any idea how to get effect in browser on code changes without refreshing the browser just only through websocket to refresh specific part only?Serous
M
0

There are 2 reasons why this doesn't function at all:

  • Binding the function in HTML component template makes infinite loop, that's a bad practice.
  • Creating a file in assets where in Angular that's static folder, so every time that folder, or external folders linked in assets in angular.json, is updated with a new file, it reloads the component

I modified my download function that returns all the text of the file through the response and then I created a blob file (https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts) where it will be downloaded when the user click the download button.

Milden answered 14/9, 2019 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.