私が望むことをやっているが、役に立たない方法でドキュメントを精査した。私は、親オブジェクトの子ルートである動的フォームコンポーネントを持っています。それはしかし動作していないhttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service階層外のコンポーネント間で通信する(Angular2)
:私はここにメソッドを使用しようとしています
{
canActivate: [AuthGuard],
path: 'profile',
component: ProfileComponent,
children: [
{
path: 'edit',
component: FormComponent,
data: {
form_title: 'Edit Profile',
action: 'current_user',
method: 'put'
}
}
]
},
:たとえば、ここでは、ユーザプロファイルおよび編集ユーザープロファイルフォームのパスです。問題は、同じサービスの異なるインスタンスを通信して通信するので、コンポーネント間に実際の「接続」がないということです。
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...//
}
私のルータの設定では、これを行うには良い方法がありますか?私はむしろ、フォームコンポーネント内のディレクティブとしてフォームコンポーネントを使用する必要はありませんが、それが唯一の方法であれば、自分のコードを調整する必要があるかもしれません。
角度2.2.0
ああそうにそれを提供!私はそれを前に試してみたが、 "FormControlServiceのプロバイダがありません"というエラーが出ていたので、私はそれを両方に別々に注入した。それがなぜそんなにうまくいかないのか理にかなっています。 –