【发布时间】:2019-06-10 17:39:48
【问题描述】:
我正在使用共享服务通过主题发出数据。在一个组件中,我尝试订阅主题数据,但它从不订阅
我正在通过组件 A 中的主题发送索引数据,如下所示 组分A
export class ComponentA {
onEditTestCase(index: number){
this.sharedService.startedEditing.next(index);
}
}
我正在使用共享服务通过主题发出索引数据。 shared.service.ts
import { Subject } from 'rxjs/Subject';
export class SharedService {
constructor(private sharedService: SharedService, private router: Router) {}
startedEditing = new Subject<number>();
}
在组件 B 中,我尝试订阅,但它从不订阅。 B组份
import { Subscription } from 'rxjs';
export class ComponentB {
subscription: Subscription;
constructor(private router: Router, private sharedService: SharedService,
private route: ActivatedRoute) {}
ngOnInit() {
this.subscription = this.sharedService.startedEditing
.subscribe((index: number) => {
this.editIndex = index;
this.editMode = true;
this.editedTestCase = this.sharedService.getTestCase(this.editIndex);
this.testForm.setValue({
testid: this.editedTestCase.testid,
testPriority: this.editedTestCase.testPriority,
testSummary: this.editedTestCase.testSummary
});
});
}
}
我在上面的代码中做错了吗?
【问题讨论】:
-
您是否在两个组件中使用相同的 sharedService 实例?
-
服务是单例吗?
-
如何在组件 A 和组件 B 中创建服务实例?您向我们展示的服务没有 @Injectable 注释,并且您没有向我们展示组件的构造函数。
-
我已经添加了构造函数代码。