简体   繁体   English

Angular 2中兄弟组件之间的数据共享

[英]Data sharing between sibling components in Angular 2

I am working on Angular 2 application in which I have two components inside a module. 我正在Angular 2应用程序中,其中模块中有两个组件。 Both modules are independant and have no parent-child relationship. 这两个模块都是独立的,没有父子关系。 First component collects some data from user which is required to be passed to second component. 第一个组件从用户收集一些需要传递给第二个组件的数据。

Component I: 组件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
            })
    }
}

Component 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  })
    }
}

Since both components are at sibling level, I think using data sharing service is a good approach. 由于两个组件都处于同级级别,因此我认为使用数据共享服务是一种不错的方法。 So, I created the data service UserService . 因此,我创建了数据服务UserService Also, User is just a model class which has many fields corresponding to a user instance. 同样, User只是一个模型类,它具有许多与用户实例相对应的字段。

User class 用户类别

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

UserService 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();
    }
}

There is no parent component. 没有父组件。 These components are inside a user module which has routes as follows: 这些组件位于用户模块内部,该用户模块的路由如下:

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

I added a user property at service level. 我在服务级别添加了一个user属性。 Inside component I, I created a user property whose value is finaly used to modify the service user property so that it is accessible in component II. 在组件I内部,我创建了一个user属性,该属性的值最终用于修改服务user属性,以便可以在组件II中对其进行访问。 During component II instantiation, I initialize its user property with the service user property. 在组件II实例化期间,我使用服务用户属性初始化其用户属性。 But, I get empty object as user this time. 但是,这次我以用户身份得到空对象。 I have registered service as providers: [UserService] in NgModule of user.module. 我已经将服务注册为providers: [UserService] user.module的NgModule中的providers: [UserService] The same issue occurs if I register it at both component's level. 如果我在两个组件级别都注册它,则会发生相同的问题。 What is the issue? 有什么问题

I could not find a proper answer for this issue. 我找不到这个问题的正确答案。 However, as evident from the above comments, the code works fine when I try it in a plunker or I use Angular CLI 1.0.2. 但是,从上面的注释中可以明显看出,当我在插件中尝试或使用Angular CLI 1.0.2时,代码可以正常工作。 Earlier, I was using quickstart seed. 之前,我使用的是quickstart种子。 As suggested by @Ahmed Musallam, I used console.log statements inside service and of course, service was being instantiated twice. 正如@Ahmed Musallam所建议的那样,我在服务内部使用了console.log语句,当然,服务被实例化了两次。 I am now using angular-cli . 我现在正在使用angular-cli This is the only solution I could figure out. 这是我能找出的唯一解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM