【问题标题】:Angular 2 same class instance between componentsAngular 2组件之间的相同类实例
【发布时间】: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


【解决方案1】:

首先我建议使用“UserService”而不是User

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

简而言之,在您的应用程序中,无论您在 providers 数组中添加服务的任何位置,都会在该组件和任何子组件中使用一个新实例。

因此,您将获得服务的新实例,当您在AppComponent 而不是loginComponent 中定义提供者时,可以将相同的实例注入那里。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2016-07-15
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2019-10-10
    • 2017-07-26
    相关资源
    最近更新 更多