Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to import JavaScript file into angular2

I am having trouble figuring out how to import a javascript file into my angular2 project. It is a file that is not a module that is apart of npm and the only instructions I have been able to find is using npm which is not an option here.

I am using angular cli and in my angular-cli.json file I have:

{
"apps": [
  "styles": [..],
  "scripts": ["../pathtomyjs/file.js"] 
]}

I ran ng build and ng serve and when I open up my app and look at the web console and try referencing the function that is in my js file, I am able to do so successfully.

Example in the console I type in:

var test = MyObject; 

and I get test = {};

However, when I try do

let test = MyObject;

in my component .ts file I get :

home.component.ts (10,11): Cannot find name 'MyObject'.)

Not sure how to do this in Angular2.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do:

declare var MyObject: any;

let test = MyObject;

Or:

let test = (<any> MyObject);

For jQuery:

declare var jQuery: any;

jQuery.ajax({ ... });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...