【问题标题】:Call Angular Component method from an imported library从导入的库中调用 Angular 组件方法
【发布时间】:2018-02-03 04:30:17
【问题描述】:

这是我的 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

【问题讨论】:

  • 除非您想导入旧项目,否则最好将 AngularJS 与 Angular2 混合使用以使用 .ts 中的所有文件。
  • 你想在 Angular 中使用第三方库吗help

标签: javascript angular angular-components


【解决方案1】:

如果您使用的是 AngularCLI,则需要将该文件添加到 angular-cli.json 文件的脚本部分。

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

无论您是否使用 Angular 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();

【讨论】:

    【解决方案2】:

    如果你想在 B 文件中使用 A 文件方法,那么你应该在 B 中导入 A

    但是你应该把你的方法放在一个服务中,然后在 wind.js 中导入服务

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 2020-10-20
      • 2023-01-08
      • 2018-04-14
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多