簡體   English   中英

從導入的庫中調用Angular Component方法

[英]Call Angular Component method from an imported library

這是我的Angular組件:

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')
    }
}

這是上面導入的wind.js文件。

export var basketModule = (function () {

return {

  init: function(){
       dataMain()
    }

}
})();

當我運行上面的代碼時,它返回一個錯誤

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

如何從導入的庫訪問Angular組件方法dataMain

如果您使用的是AngularCLI,則需要將該文件添加到angular-cli.json文件的腳本部分。

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

並且無論您是否使用角度cli,請確保將tsconfig.json文件中的'allowJs'標志設置為true。

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

然后嘗試將庫導入組件中

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

現在您應該能夠使用“ wind”名稱訪問該庫功能

 wind.dataMain();

如果要在B文件中使用A文件方法,則應在B中導入A

但是您應該將方法放在服務中,然后在wind.js中導入服務

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM