How Import JS File in angular 6?

2019-04-15 05:18发布

how can I import a js file in angular 6. I tried to implement a navbar and it contains js functions. thanks!!!

I Add my js file called nav.js

 "scripts": [
          "src/assets/js/nav.js"
        ]

2条回答
Summer. ? 凉城
2楼-- · 2019-04-15 06:00

Angular 6 has a dedicated place to declare js files within the dedicated arrays of your angular.json, under

 /projects/$(youProjectName)/architect/build/options/scripts[]

and

 /projects/$(youProjectName)/architect/test/options/scripts[]

As an example:

npm install fast-levenshtein --save

will install a js library under node-modules

The path relative to the project of the js lib file is declared like this:

"scripts": [
   "node_modules/fast-levenshtein/levenshtein.js"
]

Then declare in your component the variable(s) to use, either as described by the npm documentation or by @LuaXD

查看更多
Evening l夕情丶
3楼-- · 2019-04-15 06:08

You should include on index.html, e.g:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
   <title>A random project</title>
   <base href="/">

   <meta name="viewport" content="width=device-width, initial- 
    scale=1">
   <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
   <link rel="stylesheet" href="https://cartodb- 
  libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" 
/>
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.core.js"></script>

<app-root></app-root>
</body>
</html>

On this case I included cartodb.js library, then for use cartodb.js on any component, or service I use:

declare var cartodb: any;

At the beginning of any file (Component, Service, etc).

Note change cartodb by the name of the library you will use, for example for jquery is:

declare var jquery:any;
declare var $ :any;

You should have something like this:

import { Injectable } from '@angular/core';
// Other imports...

declare var cartodb: any;
@Injectable()
export class ARandomService {
}

P.s Search if the code you want to use doesn't exist in npm.

查看更多
登录 后发表回答