What is the equivalent of window.location.href in Angular
Asked Answered
S

1

6

In my app users can download a file as a stream from the backend which is a spring boot application, here's the backend code:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download() throws IOException {

    final InputStream fecFile = new FileInputStream(new File("C:\\file.zip"));;
    return (os) - > {
        readAndWrite(fecFile, os);
    };
}

private void readAndWrite(final InputStream is, OutputStream os) throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) >= 0) {
        os.write(data, 0, read);
    }
    os.flush();
}

Inside angular I'm using the following to download the file:

window.location.href = "http://localhost:8080/download"

Which work's fine, but I added a access token based authentication, and I cannot add a token to window.location.href, is there a way to do this in angular, I tried using the HttpModule but it's not downloading the file ( it doesn't show any response or error, even though my controller was called ), so is there a way to achive this maybe using jquery or another libreary ?

Spindlelegs answered 19/11, 2018 at 11:8 Comment(0)
D
0

You have to create a specific method (in a service or directly from the component, that's up to you, but I prefer the SOC principle that's why I separed)

On the service part :

const httpOptions = {
    headers: new HttpHeaders({
      'Key': key
    })
  };

  getFile(){

    return this.http.get("http://localhost:8080/download", httpOptions )

  }

and later in your component side:

 constructor(private myService: MyTestServiceService ) { }


 downloadFile(data: Response) {

    const blob = new Blob([data], { type: 'text/pdf' }); // pdf is an example
    const url= window.URL.createObjectURL(blob);
    window.open(url);

}

 myMethodToCallMyService() {

   this.myService.getFile()
       .subscribe(

         (data) => {
           this.downloadFile(data)
         },

        (error) => {
           console.log("Server error");
         }

       );
   }
Dickey answered 19/11, 2018 at 11:15 Comment(5)
I already specified that I used the HttpModule, but it doesn't work when it's a stream that is comming from the server.Spindlelegs
@Svg_af, in the network tab of your browser console, did you check that it was called ?Dickey
@AbdenaceurLichiheb, I dont know, but i used to download files (multipart ones), anyway, you should try with REST client (e.g: Postman), if that works , angular should so.Dickey
I tried using curl it works fine,FYI this is a stream and not multipart as I mentioned.Spindlelegs
Same thing, no file is downloading.Spindlelegs

© 2022 - 2024 — McMap. All rights reserved.