我正在开发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]
服务。如果我在两个组件的级别注册,都会发生同样的问题。什么是问题?
似乎像UserService正在实例化两次;每个组件一次。我需要它仅实例化一次,以便可以在组件之间共享数据。 – Aosis
请发布'user.module'和你的'app.module'。另外,向服务添加一个构造函数,并在其中添加一条日志语句以确保它已被多次实例化。 –
我通过https://embed.plnkr.co/FQGDe1gbSI5speWFLDLl/创建了一个plnkr。这是工作,但相同的代码不能在我的本地机器上工作。我使用了Angular quickstart种子(https://github.com/angular/quickstart)并添加了我的代码。它不工作。然而,有趣的是,如果我使用Angular CLI并添加我的代码,它将再次正常工作。有什么理由? – Aosis