我正在尝试使用此link's方法来通知组件在另一个组件上进行的操作。它建议在服务中添加Subject
变量,调用next()
方法并从需要通知的组件中订阅它。
问题是指向Subject<number>.asObservable()
的订阅方法未触发。
方案是:表单组件使用TasklistResourcesService
添加一行,然后在Http帖子之后,表单组件显示通知,服务将“间接”通知Grid组件已添加行。
表单组件:
submit({ value, valid }: { value: FormGroup, valid: boolean }) {
if (value['userId']) {
this.tasklistResourcesService.addResource(this.tasklist, +value['userId'])
.subscribe(response => {
if (response) {
this.notification.success('Sucesso!', 'Cadastro realizado.');
} else {
this.notification.error('Erro!', 'Cadastro não realizado.');
}
},
(err) => console.log(err));
}
TasklistResourcesService
private resourceAddedSource = new Subject<number>();
resourceAdded$ = this.resourceAddedSource.asObservable();
constructor(
private http: HttpClient
) { }
addResource(tasklistId: number, userId: number) {
const observable = this.http
.post<TasklistResource>(`${this.baseUrl}/${tasklistId}/resources`, {
tasklistId: tasklistId,
userId: userId
}, { observe: 'response' }).share();
observable.subscribe(response => {
this.resourceAddedSource.next(userId);
});
return observable;
}
网格组件
subscription: Subscription;
constructor(
private tasklistResourcesService: TasklistResourcesService,
private notification: NotificationsService,
private confirmation: ConfirmationService
) {
this.subscription = tasklistResourcesService.resourceAdded$.subscribe(
user => {
this.refreshGrid(); // THIS ISN'T BEING CALLED
}
);
}