简体   繁体   中英

Data sharing between sibling components in Angular 2

I am working on Angular 2 application in which I have two components inside a module. 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:

@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 . Also, User is just a model class which has many fields corresponding to a user instance.

User class

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

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. 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. During component II instantiation, I initialize its user property with the service user property. But, I get empty object as user this time. I have registered service as providers: [UserService] in NgModule of user.module. 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. Earlier, I was using quickstart seed. As suggested by @Ahmed Musallam, I used console.log statements inside service and of course, service was being instantiated twice. I am now using angular-cli . This is the only solution I could figure out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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