无法注入服务angular2-rc4

Unable to inject service angular2-rc4

我有一个 UserService,其中包含如下一些静态方法:

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 后我遇到了这个问题。 请帮忙。

我看不出你试图通过注入只有静态方法和变量的服务来完成什么。

我建议改为像单例一样使用该服务,这样注入它实际上就有意义了:

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();
     }
}

如果您想在任何组件中使用它,只需创建一个服务实例即可....

在您的构造函数中将 userinfoservice 实例设为:

constructor(private userInfoService:UserInfoService) {

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

就是这样,它工作得很好:)