我有两个服务:SharedDataService (SDS) 和 FilterService (FS)。SDS 处理我的 API 内容。它为我的用户、员工、观察结果购物。它还处理将内容发送到后端。FS处理很多,但不是屏幕上发生的所有事情。通过我的交互服务,我应该(如果我能让该死的东西工作)能够按输入日期、员工、某些类别或全部或部分连接在一起来过滤我的东西列表。
现在,这是我的问题。您如何让两个服务相互通信?我需要 FS 中来自 SDS(用户和观察)的一些信息。我如何让他们说话?
我试过:
//SharedDataService.ts
public observations: Observation[] = [];
private observationsSource = new BehaviorSubject<any>(this.observations);
observations$ = this.observationsSource.asObservable();
public getObservations(jobcode: string, loc_name: string):
Observable<Observation[]> {
return this.http
.get(API_URL + '/quick-interactions/get-observations/' + jobcode + '/' + loc_name)
.map(response => {
this.observations = response.json();
this.observations.map((observation) => new Observation(observation));
return this.observationsSource.next(this.observations);
})
.catch(this.handleError);
}
//FilterService
constructor(
private sharedDataService: SharedDataServiceService
) {
sharedDataService.employee$.subscribe(employee => {
this.employee = employee;
});
sharedDataService.observations$.subscribe(observations => {
this.observations = observations;
});
}
但这并不能满足我的需求。我尝试将其仅作为可观察量而不是行为主题。我什至尝试将其作为对返回this.observations的shareObservations方法的直接调用。他们都没有奏效。
有人有什么好主意吗?
我会完全跳过BehaviorSubject
,而是从组件调用 FilterService
中的方法,该方法在 SharedDataService
中调用方法,所以像这样:
元件:
constructor(private filterService: FilterService) { }
ngOnInit() {
this.filterService.getMyData(jobcode: string, loc_name: string)
.subscribe(data => {
console.log(data);
})
}
过滤器服务:
constructor(private sharedDataService: SharedDataService) { }
getMyData(jobcode: string, loc_name: string) {
this.sharedDataService.getObservations(jobcode: string, loc_name: string)
.map(data => {
// do whatever you need to do with your data here, then return
return data;
})
}
最后是共享数据服务,它从API获取数据:
constructor(private http: Http) { }
getObservations(jobcode: string, loc_name: string) {
return this.http.get('url here')
.map(response => response.json().map(res => new Observation(res))))
}
这是一个带有一些不同变量名称等的演示,但:)做同样的事情
如果您将代码更改为如下所示(现在没有 BehaviorSubject):
this.sharedDataService.getObservations.subscribe(observations => {
this.observations = observations;
console.log(this.observations);
});
使用控制台.log在订阅中,它输出未定义?
以下是简化版本的 SDS:
public getObservations(jobcode: string, loc_name: string):
Observable<Observation[]> {
return this.http
.get(API_URL + '/quick-interactions/get-observations/' + jobcode + '/' + loc_name)
.map(response => <Observation[]>response.json())
.do(data => console.log(JSON.stringify(data))
.catch(this.handleError);
}
下面是服务员和顾客两项服务的实现。当顾客饿了,然后使用服务员服务呼叫服务员。
@Injectable()
export class Waiter{
dish:string = 'Pizza';
constructor(){}
getSomething(){
return this.dish
}
}
@Injectable()
export class Customer{
constructor(private waiter:Waiter){}
whenHungry(){
return this.waiter.getSomething()
}
}