1
我已經走遍瞭如何做我想做的,但無濟於事的文檔。我有一個動態表單組件,它是父對象的子路徑。例如,下面是爲用戶配置文件和編輯用戶配置文件的形式路徑:組件之間的通信層次結構之外(Angular2)
{
canActivate: [AuthGuard],
path: 'profile',
component: ProfileComponent,
children: [
{
path: 'edit',
component: FormComponent,
data: {
form_title: 'Edit Profile',
action: 'current_user',
method: 'put'
}
}
]
},
我想在這裏使用的方法:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
它不工作,雖然。我認爲問題在於我注入了相同服務的不同實例進行通信,因此組件之間沒有實際的「連接」。
這裏是我的組件和我的服務,我要與通信:
ProfileComponent:
@Component({
moduleId: module.id,
selector: 'profile',
templateUrl: 'templates/profile.component.html',
providers: [ FormControlService ]
})
export class ProfileComponent implements OnDestroy{
private user: User;
private profile_sub: Subscription;
constructor(
private auth: AuthenticationService,
private fcs: FormControlService
){
this.user = auth.getUser();
this.profile_sub = fcs.resourceUpdated$.subscribe(user => {
this.user = user;
console.log(user); //nothing is logged to console here
});
}
ngOnDestroy(){
this.profile_sub.unsubscribe();
}
}
FormComponent(簡單化,以顯示相關的部分,重要的部分是的onsubmit()函數)
@Component({
moduleId: module.id,
selector: 'nw-form',
templateUrl: 'templates/form.component.html',
styleUrls: [ 'css/form.component.css' ],
providers: [ FormControlService ]
})
export class FormComponent implements OnInit, OnDestroy{
private fields: FormItem<string | Object>[][];
private form_title: string;
private form: FormBaseClass;
private model_sub: Subscription;
private submit_sub: Subscription;
formGroup: FormGroup;
constructor(
private fcs: FormControlService,
//...removed irrelevant code...//
) {
//...sets up form and populates fields if necessary...//
}
ngOnDestroy(): void {
if(this.model_sub) this.model_sub.unsubscribe();
if(this.submit_sub) this.submit_sub.unsubscribe();
}
onSubmit() {
//this is where I am trying to send data back to the profile component
this.fcs.updateResource(this.formGroup.value);
}
}
FormControlService(也簡單化了重要的部分)
@Injectable()
export class FormControlService {
private savedSource = new Subject<any>();
resourceUpdated$ = this.savedSource.asObservable();
constructor(
private clientForm: ClientForm,
private profileForm: ProfileForm
) {}
updateResource(resource: any): void {
this.savedSource.next(resource);
}
//...more functions go here...//
}
隨着我的路由器設置,有沒有更好的方法來做到這一點?我寧願不必在配置文件組件中使用表單組件作爲指令,但如果這是我可能需要調整我的代碼以適應的唯一方法。
Angular 2.2.0
是啊!我可以發誓我之前曾試過,但得到「沒有提供商的FormControlService」錯誤,所以我最終分別注入到兩者。完全理解爲什麼它不這樣工作。 –