Home > Blockchain >  Angular: Accessing assets of a lib
Angular: Accessing assets of a lib

Time:11-24

I'm trying to access some assets from one of my shared libs, but not sure how.

my structure (nx workspace)

/apps
-- my-app
   // ...

/libs
-- shared
   -- assets 
      -- resources
         -- translation.json

My shared lib has an alias defined, like: @my-company/shared.

In angular.json, I also defined my assets folder
in shared.architect.build.options like this: "assets": ["./assets"]

Now my question is: I want to fetch the translation file (via a relative path with http) into my-app. How would I reference it?

Something like @my-company/shared/assets/resources/translation.json is not working and returns a 404.

CodePudding user response:

In my Nx project I have project.json but I suspect this'll work the same in angular.json. Stick a glob pattern under the assets option:

{
  "name": "some-app",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "projectType": "application",
  "sourceRoot": "apps/some-app/src",
  "prefix": "my-org",
  "targets": {
    "build": {
      "executor": "@angular-devkit/build-angular:browser",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/some-app",
        "index": "apps/some-app/src/index.html",
        "main": "apps/some-app/src/main.ts",
        "polyfills": "apps/some-app/src/polyfills.ts",
        "tsConfig": "apps/some-app/tsconfig.app.json",
        "inlineStyleLanguage": "scss",
        "assets": [
          "apps/some-app/src/favicon.ico",
          "apps/some-app/src/assets",
          {
            "input": "libs/shared/assets/src/lib", <------------ glob
            "glob": "**.*",
            "output": "assets"
          }
        ],
        "styles": ["apps/some-app/src/styles.scss"],
        "scripts": []
      },
      ...

After that usual access to assets applies:

html

<img src="./assets/some-image.jpg" alt="image" />

ts

  getData() {
    return this.http.get('/assets/some-config.json');
  }
  • Related