简体   繁体   English

在 Angular 中的组件之间传递文件

[英]pass File between components in Angular

I want to pass a file to a second component with angular我想使用 angular 将文件传递给第二个组件

this.router.navigate(['/secondComponent'], { queryParams: { file: File}})

Or pass it via formData或者通过 formData 传递

 var formData: any = new FormData();
 formData.append("file", file);
 this.router.navigate(['/secondComponent'], { queryParams: { file: File}})

It doesn't work like this.它不像这样工作。 How can I do this?我怎样才能做到这一点? Thanks谢谢

If you want a proper async navigation between angular route components then you should consider using rxjs library which is provided by angular natively.如果您想要在 angular 路由组件之间进行适当的异步导航,那么您应该考虑使用rxjs库,它由 angular 本地提供。 You can follow the following steps to achieve that:您可以按照以下步骤来实现:

  1. Create a new service with a preferred name.使用首选名称创建新服务。
  2. Create a new Subject in the service and subscribe it in your component that is routed.在服务中创建一个新的Subject并在您的路由组件中订阅它。
  3. Emit your file object as a value in the subject before routing.在路由之前将您的文件 object 作为主题中的值发出。

You've got a few options here.你在这里有几个选择。 Passing the entire File object via query params won't work.通过查询参数传递整个File object 将不起作用。 I guess technically, it could work if you were to pass the entire file body as a string argument in the URL, but I wouldn't recommend that.我想从技术上讲,如果您将整个文件主体作为字符串参数传递到 URL 中,它可能会起作用,但我不建议这样做。

What you can do:你可以做什么:

  • Use local storage使用本地存储
  • Use a Singleton Service for storage purposes使用 Singleton 服务进行存储
  • Pass the File object in the navigation extras在导航附加文件中传递File object

To stick with your current setup, I would recommend going with the 3rd option and do something like this:为了坚持您当前的设置,我建议您使用第三个选项并执行以下操作:

this.router.navigate(['/some-route'], {state: {data: myFile}});

https://angular.io/guide/router https://angular.io/guide/router

you might want to consider passing the file id, or file name through the router and then reloading the file once you have routed.您可能需要考虑通过路由器传递文件 id 或文件名,然后在路由后重新加载文件。

The thing you have to keep in mind, is it's possible for a user to hit the browser refresh button, in which case you need to generate the entire page and all its contents based on the url.您必须记住的是,用户可能会点击浏览器刷新按钮,在这种情况下,您需要根据 url 生成整个页面及其所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM