Angular 角度-为什么可观测链不';使用switchMap将route.paramet与http.get连接时,t终止
为什么第一条链没有完成 switchMap应该取消订阅以前的可观察内容,因为http.get是一次性可观察内容,所以我认为它会记录完整Angular 角度-为什么可观测链不';使用switchMap将route.paramet与http.get连接时,t终止,angular,rxjs,angular-routing,angular-http,angular-httpclient,Angular,Rxjs,Angular Routing,Angular Http,Angular Httpclient,为什么第一条链没有完成 switchMap应该取消订阅以前的可观察内容,因为http.get是一次性可观察内容,所以我认为它会记录完整 this.http.get('assets/data/module.json').subscribe( res => { console.log(res); }, e => e, () => console.log('complete') )
this.http.get('assets/data/module.json').subscribe(
res => {
console.log(res);
},
e => e,
() => console.log('complete')
);
相反,我一直在获取http.get结果。这就是我对flatMap的期望
this.route.params
.pipe(
switchMap(params => {
return this.http.get('assets/data/module.json');
})
)
.subscribe(
res => {
console.log(res);
},
e => e,
() => console.log('complete')
);
默认的http.get将以完整的格式显示结果
this.http.get('assets/data/module.json').subscribe(
res => {
console.log(res);
},
e => e,
() => console.log('complete')
);
我想你在
switchMap
应该做的事情上弄错了<如果发出新参数,则code>switchMap将取消订阅内部可观察对象(您的http.get
调用)。一旦您的http.get
调用完成,它将不会取消对参数的订阅
您需要在管道中的switchMap操作符之前添加first()
操作符。此外,您可能希望使用switchMap的mergeMap-isntead,尽管这在您的情况下并不重要
this.route.params
.pipe(
first(),
switchMap(params => {
return this.http.get('assets/data/module.json');
})
)
.subscribe(
res => {
console.log(res);
},
e => e,
() => console.log('complete')
);
这将获取由route.params
发出的第一个参数,发出http请求,然后完成observable
可以使用的开关映射示例:
假设我们有一个搜索字段,我可以在其中输入任何内容。当我在搜索字段中输入内容时,angular将调用后端来检索搜索结果。现在,当最后一个搜索请求仍然挂起时,我可能会更改搜索条件。在这种情况下,switchMap将取消旧的get请求并发出新的get请求。我认为您在
switchMap
应该做的事情上弄错了<如果发出新参数,则code>switchMap将取消订阅内部可观察对象(您的http.get
调用)。一旦您的http.get
调用完成,它将不会取消对参数的订阅
您需要在管道中的switchMap操作符之前添加first()
操作符。此外,您可能希望使用switchMap的mergeMap-isntead,尽管这在您的情况下并不重要
this.route.params
.pipe(
first(),
switchMap(params => {
return this.http.get('assets/data/module.json');
})
)
.subscribe(
res => {
console.log(res);
},
e => e,
() => console.log('complete')
);
这将获取由route.params
发出的第一个参数,发出http请求,然后完成observable
可以使用的开关映射示例:
假设我们有一个搜索字段,我可以在其中输入任何内容。当我在搜索字段中输入内容时,angular将调用后端来检索搜索结果。现在,当最后一个搜索请求仍然挂起时,我可能会更改搜索条件。在这种情况下,switchMap将取消旧的get请求并发出新的请求。switchMap将在每次发出新参数时取消订阅以前的http observable。这如何意味着,如果前面的http observable完成,整个链就完成了?没有。您的假设不正确。每次发出新参数时,switchMap都会取消订阅以前的http observable。这如何意味着,如果前面的http observable完成,整个链就完成了?没有。你只是有一个错误的假设。