[英]Data sharing between sibling components in 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
})
}
}
第二部分:
@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實例化期間,我使用服務用戶屬性初始化其用戶屬性。 但是,這次我以用戶身份得到空對象。 我已經將服務注冊為providers: [UserService]
user.module的NgModule中的providers: [UserService]
。 如果我在兩個組件級別都注冊它,則會發生相同的問題。 有什么問題
我找不到這個問題的正確答案。 但是,從上面的注釋中可以明顯看出,當我在插件中嘗試或使用Angular CLI 1.0.2時,代碼可以正常工作。 之前,我使用的是quickstart種子。 正如@Ahmed Musallam所建議的那樣,我在服務內部使用了console.log語句,當然,服務被實例化了兩次。 我現在正在使用angular-cli
。 這是我能找出的唯一解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.