angular 2如何将自定义函数导入组件和服务

时间:2017-01-03 07:54:51

标签: angular

我有这样的功能

myHelperNumber.js

function myLittleBoy(){
  console.log('I see you)
}

如何在User.js组件或userSevicer.js服务中使用此功能?

4 个答案:

答案 0 :(得分:4)

<强> myHelperFunction.ts

export function myLittleBoy(){
  console.log('I see you)
}

<强> RegisterComponent.ts

import {myLittleBoy} from 'path to myhelperfunction.ts'

答案 1 :(得分:1)

export function myLittleBoy(){
  console.log('I see you)
}



import { Component } from '@angular/core';
declare var myLittleBoy:any;
@Component({
  selector: 'my-app',
  template: '<h1>Hello {{name}}</h1>',
})
export class AppComponent  { 

    constructor(private __jsmodel:JSmodelEvents){
        myLittleBoy();

    }

}

答案 2 :(得分:0)

import {myHelperNumber} from 'your path';
export class AppComponent{
   constructor(private helpNum: myHelperNumber){
      // Now you can use myLittleBoy function anywhere inside the AppComponent Class
      // Like below shown: 
      // this.helpNum.myLittleBoy();
   }
}

确保myHelperNumber文件是可导出的格式。

答案 3 :(得分:-1)

myHelperNumber.ts:

export const function myLittleBoy(){
  console.log('I see you)
}

然后在User.ts或userService.ts

import {myLittleBoy} from './myHelperNumber';
// and just use it in this class