2016-08-24 20 views
0

所以,即时通讯相当新的角2,到目前为止好。 即时通讯有问题(可能是因为如此使用角1)是我需要类用户是全局性的,并在不同的组件之间使用它。组件之间的角2同一类实例

在我的情况下,我得到了一个User类和即时登录用户在一个组件。

@Component({ 
    selector: 'login', 
    templateUrl: 'app/login/login.html', 
    providers: [User] 
}) 
export class loginComponent { 
    submitted = false; 
    username : string; 
    password : string; 
    constructor(public user : User){} 
    onSubmit(event) { //form event 
    event.preventDefault(); 
    this.user.login(this.username,this.password,() =>{this.router.navigateByUrl('dashboard')} 

所以在用户的​​登录方法中,路由器我有asigned到路由仪表盘上的部件diferent设定的用户的内部变量,如名字,姓氏,等等 。 因此,当我导入User时,我得到了该类的新实例。我如何在班上获得数据?

+0

不要在组件的提供程序中声明用户。在根NgModule的提供者中声明它。 –

+0

...我没有,一个ngModule,即时引导一个mainComponent ...就像文档说...我注入提供商在该组件和工作,我想就像角度为1的旧范围事情 –

+0

这必须是那么您正在查看的旧文档。阅读https://angular.io/docs/ts/latest/guide/ngmodule.html。但是,如果您在根组件的提供者中声明它,则会产生相同的效果。 –

回答

2

首先我会建议使用'UserService'而不是User

您正在查找Application-wide dependencies需要提供更高级别,最好在您的AppComponentAppModule

简而言之,在providers数组中添加服务的应用程序中,将在该组件和任何子组件中使用新实例。

因此,当您在AppComponent中定义提供程序而不是在loginComponent中时,可以在该处注入同一个实例,从而获得服务的新实例。

希望这有助于!

+0

是的,在行动中,thx! –

+0

很酷的工作,干杯! –