[英]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:您可以按照以下步骤来实现:
Subject
in the service and subscribe it in your component that is routed.Subject
并在您的路由组件中订阅它。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:你可以做什么:
File
object in the navigation extrasFile
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.