【发布时间】:2016-08-25 05:27:35
【问题描述】:
所以,我对 angular 2 很新,到目前为止一切都很好。 我遇到的问题(可能是因为习惯了角度 1)是我需要类用户是全局的并在不同的组件之间使用它。
在我的例子中,我有一个 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')}
所以 user 中的方法 login 是设置用户的内部变量,如姓名、姓氏等。
在路由器中,我有一个分配给路由仪表板的不同组件。
所以当我导入User 时,我得到了该类的一个新实例。我怎样才能维护类中的数据?
【问题讨论】:
-
不要在组件的提供者中声明用户。在根 NgModule 的提供者中声明它。
-
...我没有,一个 ngModule,我在引导一个 mainComponent...就像文档说...我在该组件上注入了提供程序并工作,我想就像旧范围的东西角度为 1
-
那一定是您正在查看的旧文档。阅读angular.io/docs/ts/latest/guide/ngmodule.html。但是如果你在根组件的提供者中声明它,你会得到同样的效果。
标签: angular typescript