我在一个窗口中有两个组件。首先是日历,通过单击“确定”按钮,它会发送一些数据进行维修。通过邮政请求服务得到一些回应。 我需要立即在另一个组件中显示响应的结果。我想,我需要为此制作共享服务,但我该怎么做呢? 如何在共享服务中订阅响应,因为它需要参数?
服务:
getData(model:any): Observable<any>{
return this.http.post("http://127.0.0.1:5000/schedule",JSON.stringify(model))
.map((response:Response)=>{
this.schedule = response.json();
return response.json();
});
}
calendar.component:
getData(){
this.http.getData({id_teacher: this.id,date: this.model.formatted}).subscribe(result => {
this.data = result;
// console.log(this.data)
});
// console.log(this.http.schedule);
}
答案 0 :(得分:0)
您需要的只是Subject
:
只需按照以下代码中的// Execution flow
进行操作,您也会明白流程。
服务:
public scheduleData : Subject<any> = new Subject<any>(); // create a Observable Subject
getData(model:any): Observable<any>{ // Execution flow 2
return this.http.post("http://127.0.0.1:5000/schedule",JSON.stringify(model))
.map((response:Response)=>{
this.scheduleData.next(response.json()); // This will emit event asap change // Execution flow 3
});
}
calendar.component.ts:
// just call this from component 1
this.http.getData({id_teacher: this.id,date: this.model.formatted}).subscribe(); // Execution flow 1
calendar2.component.ts:
// component 2 : this will be called asap any changes in scheduleData
// Execution flow 4
this.http.scheduleData.subscribe(result =>
this.data = result; // Execution flow 5
// console.log(this.data)
});
服务必须与这两个组件共享