Reputation: 1985
I'm having one UserService which contains some static methods as below:
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;
}
}
I'm injecting it in boot.ts as shown below:
bootstrap(AppComponent, [ UserInfoService])
I'm using this service in another component as below:
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();
}
}
This NavigationComponent calls is not able to access UserInfoService. Note: This was working with angular2-rc1. I'm facing this issue after upgrading to rc4. Please help.
Upvotes: 0
Views: 217
Reputation: 3544
just make a instance of your service if you want to use it in any of your component ....
In your constructor make userinfoservice instance as:
constructor(private userInfoService:UserInfoService) {
//......now you can use your functions by
userInfoService.getUserInfo()
}
that's it ,it works fine with it :)
Upvotes: 2
Reputation: 23506
I can't see what you're trying to accomplish by injecting a service which only has static methods and variables.
I'd suggest using the service like a singleton instead, so that injecting it actually makes some sense:
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;
}
}
And in your component:
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();
}
}
Upvotes: 1