2017-05-03 70 views
0

我正在开发Angular 2应用程序,其中模块内有两个组件。两个模块都是独立的,没有父子关系。第一个组件收集用户需要传递给第二个组件的一些数据。Angular 2中的同级组件之间的数据共享

成分I:

@Component({ 
    selector: 'user-otp-generation', 
    templateUrl: `../partials/user-management/user-generate-otp.html`, 
    moduleId: module.id, 
    // providers: [UserService] 
}) 

export class UserOtpGenerationComponent{ 
constructor(private UserService: UserService) { } 

user: User = new User(); 

onSubmit(){ 
    this.UserService.generateOTP(this.user.phone) 
     .then(response => { 
       this.UserService.setUserProperty('phone', this.user.phone); //From user input 
       this.UserService.setUserProperty('otp', response.otp); //From API response 
      }) 
    } 
} 

组分II:

@Component({ 
    selector: 'user-authentication', 
    templateUrl: `../partials/user-management/user-authentication.html`, 
    moduleId: module.id, 
    // providers: [UserService] 
}) 

export class UserAuthenticationComponent { 
    constructor(private UserService: UserService) { 
     this.user = UserService.getUser(); 
    } 

    user:User; 

    onSubmit(){ 
     this.UserService.verifyOTP(this.user.otp) 
      .then(response => { //Do something }) 
    } 
} 

由于这两种成分在同级的水平,我想用数据共享服务是一个不错的办法。所以,我创建了数据服务UserService。此外,User只是一个模型类,它有许多与用户实例相对应的字段。

用户类

export class User { 
    phone: string; 
    otp: string; 
    reference_id: string; 
    // Many other similar fields 
} 

UserService

@Injectable() 
export class UserService { 
    private user: User = new User(); 

    getUser(){ 
     return this.user; 
    } 

    setUserProperty(key, value){ 
     this.user[key] = value; 
    } 

    generateOTP(phone: string): Promise<any>{ 
     return this.http.get('some-url').toPromise(); 
    } 
} 

没有父组件。这些组件是具有路由如下用户模块内:

const userRoutes: Routes = [ 
    {path: '', redirectTo: 'generate-otp', pathMatch: 'full'}, 
    {path: 'generate-otp', component: UserOtpGenerationComponent}, 
    {path: 'authenticate', component: UserAuthenticationComponent} 
] 

我加入在服务级别属性user。在组件I内部,我创建了一个user属性,其值最终用于修改服务user属性,以便在组件II中可访问该属性。在组件II实例化过程中,我使用服务用户属性初始化其用户属性。但是,这次我用空的对象作为用户。 我在user.module的NgModule中注册了providers: [UserService]服务。如果我在两个组件的级别注册,都会发生同样的问题。什么是问题?

+0

似乎像UserService正在实例化两次;每个组件一次。我需要它仅实例化一次,以便可以在组件之间共享数据。 – Aosis

+1

请发布'user.module'和你的'app.module'。另外,向服务添加一个构造函数,并在其中添加一条日志语句以确保它已被多次实例化。 –

+0

我通过https://embed.plnkr.co/FQGDe1gbSI5speWFLDLl/创建了一个plnkr。这是工作,但相同的代码不能在我的本地机器上工作。我使用了Angular quickstart种子(https://github.com/angular/quickstart)并添加了我的代码。它不工作。然而,有趣的是,如果我使用Angular CLI并添加我的代码,它将再次正常工作。有什么理由? – Aosis

回答

0

我找不到这个问题的正确答案。但是,从上面的评论中可以看出,当我在一个plunker中尝试它时,代码工作正常,或者我使用Angular CLI 1.0.2。早些时候,我使用快速启动种子。 正如@Ahmed Musallam建议的那样,我在服务中使用了console.log语句,当然,服务被实例化了两次。我现在使用angular-cli。这是我能想出的唯一解决方案。

相关问题