首页 > 解决方案 > Angular中window.location.href的等价物是什么

问题描述

在我的应用程序中,用户可以从作为 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();
}

在 Angular 内部,我使用以下内容下载文件:

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

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

标签: angularstream

解决方案


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

在服务部分:

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

  getFile(){

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

  }

稍后在您的组件方面:

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

       );
   }

推荐阅读