2016-07-14 137 views
0

我有一个UserService其中包含如下一些静态方法:如下所示无法注入服务angular2-RC4

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

@Injectable() 
export class UserInfoService { 
    private static _userInfo: any; 

    static put(userInfo:any) { 
     this._userInfo = userInfo; 
    } 
    static getRole() : string { 
     if (this._userInfo) { 
      return this._userInfo.role; 
     } 
     return ''; 
    } 
    static getUserInfo() : string { 
     return this._userInfo; 
    } 
} 

我注入它在boot.ts:

bootstrap(AppComponent, [ UserInfoService]) 

我在另一个组件使用此服务如下:

import {Component} from '@angular/core'; 
import {UserInfoService} from "../service/user.info"; 

@Component({ 
    selector: 'nav-bar', 
    templateUrl: 'template/navbar.html' 
}); 
export class NavigationComponent { 
    constructor() { 
     this.userInfo = UserInfoService.getUserInfo(); 
    } 
} 

这NavigationComponent调用无法访问UserInfoService。 注意:这与angular2-rc1一起工作。升级到rc4后,我遇到了这个问题。 请帮忙。

+0

你必须注入''里面constructor' UserInfoService'得到它的实例.. –

回答

1

我看不到你想要通过注入只有静态方法和变量的服务来实现什么。

我建议使用像一个单独的服务,而不是,所以注射它实际上有一定道理:

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

@Injectable() 
export class UserInfoService { 
    private _userInfo: any; 

    put(userInfo:any) { 
     this._userInfo = userInfo; 
    } 
    getRole() : string { 
     if (this._userInfo) { 
      return this._userInfo.role; 
     } 
     return ''; 
    } 
    getUserInfo() : string { 
     return this._userInfo; 
    } 
} 

而在你的组件:

import {Component} from '@angular/core'; 
import {UserInfoService} from "../service/user.info"; 

@Component({ 
    selector: 'nav-bar', 
    templateUrl: 'template/navbar.html' 
}); 
export class NavigationComponent { 
    userInfo: string; 

    constructor(private _userInfoService: UserInfoService) { 
     this.userInfo = _userInfoService.getUserInfo(); 
    } 
} 
+0

我用静态方法,使我没有在构造函数来创建实例它一直工作到rc1。但看起来事情已经改变了与rc4这是从工作中断这一点。无论如何,我将在构造函数中创建实例并使用它。谢谢 – Krishna

+0

如果它完全是静态的,则不需要注入它。 – rinukkusu

+0

这意味着我不需要使用@Injectable,我不需要在bootstrap('appComponent',[])中提供? – Krishna

2

只是做的比如你服务,如果你想在任何组件使用它...

在您的构造函数使userinfoservice实例为:

constructor(private userInfoService:UserInfoService) { 

    //......now you can use your functions by 
    userInfoService.getUserInfo() 
} 

就是这样,它的工作原理与它的罚款:)