2017-09-16 30 views
0

私はを使用しています。角は4.2.4です。角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; 
    } 
} 

コンポーネント例:

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がいないことを私のために働く...

+0

なぜ変数の代わりに関数があるのですか? – Aravind

+0

http://plnkr.co/edit/ihdogKe9PBs8bce06cZZ?p=previewそれはこのplunkerで働いています.. – echonax

答えて

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ください)変更templateUrltemplate

@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) { } 
} 
+0

ファイルのパスである前に "template"を忘れています でも同じエラーがあります –

+0

'Global '名前 –

+0

何も変わりません。 3-4の異なる名前を試してください –

0

に次のような修飾子を使用する必要があります。public range:あなたが好きな変数を宣言する場合

public; 
private; 
protected; 

;

+0

助けられませんでした。まだ何らかの誤りがある –

関連する問題