简体   繁体   中英

Call Angular Component method from an imported library

Here is my Angular component:

import { basketModule } from './wind'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {



    constructor(){
    }

    ngOnInit(){
        basketModule.init()
    }

    public dataMain(){
        alert('hi')
    }
}

Here is the wind.js file which is imported above.

export var basketModule = (function () {

return {

  init: function(){
       dataMain()
    }

}
})();

When I run the above code, it returns an error that

core.es5.js:1020 ERROR ReferenceError: dataMain is not defined

How to access the Angular component method dataMain from the imported library ?

If you're using AngularCLI, you will need to add that file to the scripts section of the angular-cli.json file.

"scripts": [
     // path to script here in quotes
 ],

And regardless of whether you're using angular cli, make sure the 'allowJs' flag in your tsconfig.json file is set to true.

 {
     "compilerOptions": {
       "target": "es5",
       "sourceMap": true,
       "allowJS": true   // this one
   }
}

Then try importing the library in your component

import * as wind from './path/to/lib/wind.js'

Now you should be able to access that libraries functions using the 'wind' name

 wind.dataMain();

If you want an A file methode in a B file so you should import A in B

But you should put your methode in a service and then import service in wind.js

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