DevRight
DevRight

Reputation: 395

Angular 2. Resource's fails to load in html page

I am building an Angular 2 application. When I ng-serve the application, the css and image filed to load, with the following errors. enter image description here

I have moved the css link above the js link, which did not work.
I have also added the full path to the files, instead of the existing.

Below is the project structure.

enter image description here

The html code for index.html

<html>
<head>
  <meta charset="utf-8">
  <title>Front</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">


  <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
  <script src="resources/js/semantic.min.js"></script>

  <link rel="stylesheet" type="text/css" class="ui" href="resources/css/semantic.css" />
  <link rel="stylesheet" type="text/css" class="ui" href="resources/css/main.css" />

</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

I have ran into similar issues before with Angularjs and my fix was to, keep moving and changing the links until it worked. Could someone explain why this happens and what are the best practices to avoid this happening in the future.

Upvotes: 0

Views: 83

Answers (1)

LLai
LLai

Reputation: 13406

You have to add your resources to your assets field in the angular-cli.json. This makes them available when you do ng serve

"assets": [
    "resources"
]

This will copy your resources directory into the assets folder (in your build) for both ng build & ng serve. Now replace resources with assets in your paths

<script src="assets/js/semantic.min.js"></script>

<link rel="stylesheet" type="text/css" class="ui" href="assets/css/semantic.css" />
<link rel="stylesheet" type="text/css" class="ui" href="assets/css/main.css" />

As an alternative, I would add these files to the angular-cli.json instead of loading them in index.html

"styles": [
    "resources/css/semantic.css",
    "resources/css/main.css"
],
"scripts": [
    "resources/js/semantic.min.js"
]

I prefer this because those files will be bundled together by webpack, saving on some http requests. Plus I believe the json file is easier to read then index.html, when it comes to dependencies.

Upvotes: 1

Related Questions