【问题标题】:Unable to inject service angular2-rc4无法注入服务 angular2-rc4
【发布时间】:2016-11-17 00:41:29
【问题描述】:

我有一个包含一些静态方法的 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 后我遇到了这个问题。 请帮忙。

【问题讨论】:

  • 你在constructor 中注入了UserInfoService 来获取它的实例..

标签: typescript angular angular2-services


【解决方案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();
     }
}

【讨论】:

  • 我使用了静态方法,这样我就不必在构造函数中创建实例,并且它一直工作到 rc1。但看起来 rc4 发生了一些变化,这中断了它的工作。无论如何,我会在构造函数中创建实例并使用它。谢谢
  • 如果它是完全静态的,你就不需要注入它。
  • 这意味着我不需要使用@Injectable 也不需要提供 bootstrap('appComponent',[]) ??
  • 没错。如果方法是静态的,则无需实例化类即可访问它们,因此无需在任何地方注入。
  • 那么为什么它在我的代码“UserInfoService.getUserInfo()”中不起作用。我不认为仅仅添加 @Injectable 注释就可以阻止我访问它的声明方法。
【解决方案2】:

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

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

constructor(private userInfoService:UserInfoService) {

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

就是这样,它可以正常工作:)

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 2016-11-24
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多