如何从回调中返回可观察的
我有一项服务,要实现SDK的逻辑。 从这个SDK我想调用一个返回有效载荷的事件。
我想创建一种调用事件的方法,并将其包裹在可观察的情况下,以订阅事件的响应。 我还创建了一个接口,以确保SDK响应的类型安全。
这就是到目前为止创建的内容:
export interface SdkPayload{
avatar,
name,
jobTitle,
availability
}
export class TestService {
sdk:someSDK;
//method that returns an Observable
getPayload$(): Observable<SdkPayload[]> {
//创建接口中定义的类型的新观察。 返回新的观察值&lt; sdkpayload []&gt;(((subscriber)=&gt; { const callbackFunction = (sdkpayload:sdkpayload [])=&gt; {
this.someSDK.on('connected', (payload) => {
payload.greeting.agent.avatar,
payload.greeting.agent.name,
payload.greeting.agent.jobTitle,
payload.availability;
});
subscriber.next(sdkPayload);
};
this.customerSDK.on('connected', callbackFunction);
return () => {
this.customerSDK('off', callbackFunction);
};
});
}
组件:
export class AppComponent{
payloadResults$: Observable<SdkPayload[]>;
constructor (private service:TestService){}
callMethod(){
this.payloadResults$=this.service.getPayload$();
}
}
我感觉到我从SDK中使用的事件未正确实现或正确地包装在可观察到的情况下。最后,我的目标是将SDK响应包装成可观察的响应,以便我可以订阅其响应。
I have a service in which I want to implement the logic of an SDK.
From this SDK I want to call an event that returns a payload.
I want to create a method in which the event is called and wrap it in an Observable to be able to subscribe to the response of the event.
I as well created an interface in order to assure type-safety of the sdk's response.
This is what has been created so far:
export interface SdkPayload{
avatar,
name,
jobTitle,
availability
}
export class TestService {
sdk:someSDK;
//method that returns an Observable
getPayload$(): Observable<SdkPayload[]> {
//create new Observable of type defined in Interface
return new Observable<SdkPayload[]>((subscriber) => {
const callbackFunction =
(sdkPayload:SdkPayload[]) => {
this.someSDK.on('connected', (payload) => {
payload.greeting.agent.avatar,
payload.greeting.agent.name,
payload.greeting.agent.jobTitle,
payload.availability;
});
subscriber.next(sdkPayload);
};
this.customerSDK.on('connected', callbackFunction);
return () => {
this.customerSDK('off', callbackFunction);
};
});
}
Component:
export class AppComponent{
payloadResults$: Observable<SdkPayload[]>;
constructor (private service:TestService){}
callMethod(){
this.payloadResults$=this.service.getPayload$();
}
}
I have the feeling that the event that I use from the sdk is not correctly implemented or correctly wrapped in the Observable. In the end my goal is to wrap the SDK Response into an Observable, so that I can subscribe to its response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个主题。
在服务类中,主题:
在您的getPayload函数上,您可以使用上面的函数触发新值,而不是可观察到:
使用您可以使用新的可观察格式
然后在组件类上
You could create a subject.
On Service Class init a subject:
On your getPayload function You could use above function to trigger the new value as observable instead of:
use
Then on your component class you could use the new observable format