Subject.subscribe在ngOnInit中未触发

时间:2019-05-27 07:08:10

标签: angular observable angular2-observables behaviorsubject subject-observer

我已经在 service.ts 中定义了主题 onEditItem()中的detail.component.ts传递.next()中id的值,并且主题在 new.component.ts 中被订阅 但是订阅不起作用。订阅是在 new.component.ts

ngOnInit中完成的。

id的值已成功在onEditItem()中传递,但是订阅无法正常工作。我尝试在订阅内进行console.log检查。但是控制台上什么也没打印。

details.component.html

<a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>

details.component.ts

  onEditItem(){this.contactService.startedEditing.next(this.id);}

contactService.ts

export class ContactService {
  startedEditing =new Subject<number>();
}

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
      })
    }
  );
} 

我希望new.component.html中定义的表单应该使用来自details组件的值进行初始化,但是订阅在ngOnInit中不起作用。

3 个答案:

答案 0 :(得分:2)

对象需要发出该值,以便观察者对事件采取行动。

这意味着您必须单击Div或切换到BehaviorSubject,这将返回订阅时流的最后一个值。

答案 1 :(得分:0)

您必须更改服务

startedEditing =new Subject<number>();
startedEditing$: Observable<any> = this.startedEditing.asObservable();

 shareData(data)
  {
    this.startedEditing.next(data)
  }

和您的 details.component.ts

 onEditItem(){
  this.contactService.shareData(this.id)
  }

,最后进入 new.component.ts

ngOnInit() {
  this.contactService.startedEditing$.subscribe(res=>{ 
 console.log(res)// you can get the data here
}

仅此而已

答案 2 :(得分:0)

主题是可观察者和观察者的混合版本。因此,它将显示这两种行为,因此不必创建单独的可观察对象。

我为您的问题创建了一个简单的stackbitz。请检查(https://stackblitz.com/edit/angular-ypeadt)希望有帮助。干杯!