简体   繁体   中英

How to fetch a list of all svg files from an angular application directory?

I want to fetch a list of all .svg files inside a specific folder of my Angular 4 application. Therefore I am already declaring the folder in my angular-cli.json file via

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "favicon.ico",
        "assets",
        {
          "glob": "**/*.svg",
          "input": "../node_modules/..../assets/images",
          "output": "./assets/images"
        }
      ],
      "index": "index.html",
      "main": "ma...

How am I able now to read a list of all .png files inside my ./assets/images directory?
The list should be loaded inside a standard angular component. Afterwards I want iterate over the list using a simple for loop. I can do the last part by my own if some of you can tell me how to get the list.


EDIT

The content of the directory looks something like this

images
|--file_1.svg
|--file_2.svg
|--file_3.svg
└--file_4.svg

If I try to acces the url HOST:PORT/assets/images/file_1.svg the image is displayed correct, but if I try to list all files of the directory using HOST:PORT/assets/images an HTTP 404 occurs.

Here is the constructor of my component:

constructor(private http: Http) {
   this.http.get('./assets/images').subscribe(res => console.log(res));
}

I have tried my best to find a solution for this but it appears impossible as Javascript does not have access to the file structure. The best solution I can find is to create a list of icons in a json, request the file and then store the contents for later user.

I have found this example.

As accessing file from assets folder is easy, so we can exploit it
and we can store an array of icon file names in the file say, icons.json .

1. Create icons.json as following in the assets folder-

{  // ---------- icons.json---------
  "icons-array" : ["icon-name1", "icon-name2", "icon-name3"]
}

2. Keep icon-name1.svg , icon-name2.svg , icon-name3.svg file in the assets/icons folder.
3. Read icons-json file at start-up of the angular application.
How to read file at Angular Application Start-up

4. After reading icons.json content, store value of icons-array property into a global accessible array, say globalAccessibleIconsArray .
5. And use the array as-

for (const icon of globalAccessibleIconsArray) {
      this.matIconRegistry.addSvgIconInNamespace(
        'my-namespace',
        icon,
        domSanitizer.bypassSecurityTrustResourceUrl(`./assets/icons/${icon}.svg`)
      );
    }


So, for Adding a new icon

  • you have to put the new icon file in the assets/icon folder, and
  • add the new file name in the icons.json file present in the assets folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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