Angular 4:全局变量未定义

时间:2017-09-16 08:18:38

标签: angular

我使用 Angular ^ 4.2.4

所有组件都需要全局功能范围

import { Injectable } from '@angular/core';

@Injectable()
export class Global {

  range:object = function(n:number){

    var vs = [];

    for( var i=0; i < n; i++ )
      vs.push(i);

    return vs;
  }
}

root的组件示例:

import { Component } from '@angular/core';
import { Global } from "./global";

@Component({
  selector: 'app-root'
  ,templateUrl: '<ul><li *ngFor="let i of global.range(5)">{{i}}</li></ul>'
  ,providers: [ Global ]
})
export class AppComponent {
  constructor( public global: Global ){}
}

但是控制台日志是:

ERROR TypeError: Cannot read property 'range' of undefined
    at Object.eval [as updateDirectives] (AppHome.ngfactory.js:19)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13065)
    at checkAndUpdateView (core.es5.js:12245)
    at callViewAction (core.es5.js:12610)
    at execComponentViewsAction (core.es5.js:12542)
    at checkAndUpdateView (core.es5.js:12251)
    at callViewAction (core.es5.js:12610)
    at execEmbeddedViewsAction (core.es5.js:12568)
    at checkAndUpdateView (core.es5.js:12246)
    at callViewAction (core.es5.js:12610)

instruction对我不起作用......

2 个答案:

答案 0 :(得分:1)

1)制作方法public

@Injectable()
export class Global {

   public range(n:number): number[] {
     const vs: number[] = [];

     for( let i = 0; i < n; i++ ) {
        vs.push(i);
     }

     return vs;
   }

}

2)将templateUrl更改为template

@Component({
   selector: 'app-root',
   template: '<ul><li *ngFor="let i of global.range(5)">{{ i }}</li></ul>',
   providers: [Global]
})
export class AppComponent {
   constructor( public global: Global ) { }
}

答案 1 :(得分:0)

您应该使用以下修饰符:

public;
private;
protected;

当您声明变量时:public range;