Son*_*ali 3 observable subject-observer behaviorsubject angular2-observables angular
我已经在我的service.ts中定义了主题
,onEditItem()其中detail.component.ts传递了 id 的值,并且在new.component.ts.next()中订阅了主题
,但订阅不起作用。订阅是在new.component.ts 中完成的ngOnInit
id 值传入成功,onEditItem()但订阅失败。我尝试在订阅内进行 console.log 检查。但控制台中没有打印任何内容。
在details.component.html中
<a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>
Run Code Online (Sandbox Code Playgroud)
在详细信息.component.ts中
onEditItem(){this.contactService.startedEditing.next(this.id);}
Run Code Online (Sandbox Code Playgroud)
在contactService.ts中
export class ContactService {
startedEditing =new Subject<number>();
}
Run Code Online (Sandbox Code Playgroud)
在new.component.ts中
ngOnInit() {
this.subscription = this.contactService.startedEditing.subscribe(
(index: number) => {
console.log(index);
this.editedItemIndex = index;
console.log(this.editedItemIndex);
this.editMode = true;
this.editedItem = this.contactService.getContacts(index);
this.editForm.setValue({
name: this.editedItem.name,
address: this.editedItem.address
})
}
);
}
Run Code Online (Sandbox Code Playgroud)
我预计中定义的表单new.component.html应使用详细信息组件中的值进行初始化,但订阅在 中不起作用ngOnInit。