Angular 中的 window.location.href 相当于什么

Svg*_*_af 6 stream angular

在我的应用程序中,用户可以从后端下载文件作为流,这是一个 Spring Boot 应用程序,这是后端代码:

@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();
}
Run Code Online (Sandbox Code Playgroud)

在角度内部,我使用以下命令来下载文件:

window.location.href = "http://localhost:8080/download"
Run Code Online (Sandbox Code Playgroud)

哪个工作很好,但是我添加了基于访问令牌的身份验证,并且我无法将令牌添加到 window.location.href,有没有办法以角度方式执行此操作,我尝试使用 HttpModule 但它没有下载文件(它不即使我的控制器被调用,也不会显示任何响应或错误),那么有没有办法使用 jquery 或其他库来实现此目的?

sel*_* mn 0

你必须创建一个特定的方法(在服务中或直接从组件中,这取决于你,但我更喜欢 SOC 原则,这就是我分开的原因)

在服务部分:

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

  getFile(){

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

  }
Run Code Online (Sandbox Code Playgroud)

然后在你的组件端:

 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");
         }

       );
   }
Run Code Online (Sandbox Code Playgroud)