bor*_*net 15 rxjs typescript angular
我试图使用switchMap取消Angular2中以前的任何http调用.代码基本上是
var run = ():Observable<any> => {
var url = 'http://...'
return this._http.get(url)
.map(result => {
return var xmlData:string = result.text()
});
}
function pollTasks() {
return Observable.of(1)
.switchMap(() => run())
.map(res => res)
}
// caller can do subscription and store it as a handle:
let tasksSubscription =
pollTasks()
.subscribe(data => {
console.log('aa'+data)
});
Run Code Online (Sandbox Code Playgroud)
所以我连续几次调用整个源并收到几个回复(即:aa + data)
我的印象是switchMap应该取消以前的调用.
Cal*_*den 21
请求需要源自相同的基础流.这是一个工厂函数,它将创建一个应该做你想做的http服务实例:
function httpService(url) {
// httpRequest$ stream that allows us to push new requests
const httpRequest$ = new Rx.Subject();
// httpResponse$ stream that allows clients of the httpService
// to handle our responses (fetch here can be replaced with whatever
// http library you're using).
const httpResponse$ = httpRequest$
.switchMap(() => fetch(url));
// Expose a single method get() that pushes a new
// request onto the httpRequest stream. Expose the
// httpResponse$ stream to handle responses.
return {
get: () => httpRequest$.next(),
httpResponse$
};
}
Run Code Online (Sandbox Code Playgroud)
现在客户端代码可以使用这样的服务:
const http = httpService('http://my.api.com/resource');
// Subscribe to any responses
http.httpResponse$.subscribe(resp => console.log(resp));
// Call http.get() a bunch of times: should only get one log!!
http.get();
http.get();
http.get();
Run Code Online (Sandbox Code Playgroud)
constructor(private _http:Http, private appStore:AppStore) {
this.httpRequest$ = new Subject();
this.httpRequest$
.map(v=> {
return v;
})
.switchMap((v:any):any => {
console.log(v);
if (v.id==-1||v.id=='-1')
return 'bye, cancel all pending network calls';
return this._http.get('example.com)
.map(result => {
var xmlData:string = result.text()
});
}).share()
.subscribe(e => {
})
...
Run Code Online (Sandbox Code Playgroud)
并推送数据:
this.httpRequest$.next({id: busId});
Run Code Online (Sandbox Code Playgroud)
这很好用,我现在可以有一个服务,我可以管理所有网络电话,以及取消之前的电话...
看到下面的图片,当新的电话进来时,先前的电话被取消.请注意我如何设置慢速网络,延迟4秒,以提供所有正常工作...
我认为当你使用switchMap操作符时,你只能取消当前数据流中的请求。我的意思是在同一个可观察链上发生的事件......
如果您多次调用您的pollTasks方法,您将无法取消以前的请求,因为它们不会位于同一数据流中......每次调用该方法时,您都会创建一个可观察链。
我不知道你如何触发你的请求的执行。
如果您想每 500 毫秒执行一次请求,您可以尝试以下操作:
pollTasks() {
return Observable.interval(500)
.switchMap(() => run())
.map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果 500ms 后还有正在进行的请求,它们将被取消以执行新的请求
使用该方法,您只需要调用一次该pollTasks方法即可。
您还可以根据用户事件触发异步处理链。例如,当输入中填充字符时:
var control = new Control();
// The control is attached to an input using the ngFormControl directive
control.valueChanges.switchMap(() => run())
.map(res => res.json())
.subscribe(...);
Run Code Online (Sandbox Code Playgroud)
有一项建议可以更轻松地链接/启动 DOM 事件的处理链 ( fromEvent)
请参阅此链接:
| 归档时间: |
|
| 查看次数: |
9816 次 |
| 最近记录: |