Angular http调用/RxJs之前的操作
在api调用之前,在angular中是否有使用rxjs的调用操作解决方案 例如,我想要:Angular http调用/RxJs之前的操作,angular,rxjs,observable,Angular,Rxjs,Observable,在api调用之前,在angular中是否有使用rxjs的调用操作解决方案 例如,我想要: 启动装载机 从服务器获取数据 端部装载机 我想在一个“管道”里做这件事 return this.customersService .getById(id) .pipe( actionBefore( () => this.startLoading() ) // <= I need this switchMap(async (data) =&
return this.customersService
.getById(id)
.pipe(
actionBefore( () => this.startLoading() ) // <= I need this
switchMap(async (data) => {
this.customer$.next(data);
return data;
}),
finalize(() => this.endLoading())
);
返回此.customersService
.getById(id)
.烟斗(
actionBefore(()=>this.starting())//{
此.customer$.next(数据);
返回数据;
}),
完成(()=>this.endLoading())
);
我认为下面这样的方法可以达到目的,但我认为如果你把惊人的加载
放在整个可观察管道之外,阅读起来会更容易
返回(空)
.烟斗(
点击(()=>this.starting()),
switchMap(()=>this.customersService.getById(id)),
点击(数据=>this.customers$.next(数据)),
完成(()=>this.endLoading())
);
或者,使用延迟:
返回延迟(()=>{
这是令人吃惊的;
返回此.customerService.getById(id)
.烟斗(
点击(数据=>this.customers$.next(数据)),
完成(()=>this.endLoading())
);
});
另一种方法是,使用新的可观察对象
:
返回新的可观察对象(订户=>{
这是令人吃惊的;
this.customerService.getById(id)
.烟斗(
点击(数据=>this.customers$.next(数据)),
完成(()=>this.endLoading())
).认购(认购人);
});
您可以在可观察调用之前开始加载,并在管道中的最后一个操作符中结束加载:
this.startLoading();
返回此。CustomerService
.getById(id)
.烟斗(
地图(数据=>{
此.customer$.next(数据);
此参数为.endLoading();
返回数据;
}),
catchError((err)=>{
this.endLoading();//如果出现错误,也要完成加载
投掷者(错误);
})
);
您可以使用角度拦截器来实现这一点。因此,每当HTTP请求进行时,都会显示加载。为此,您需要创建一个加载服务,即加载拦截器(您还可以创建一个加载组件来实现进度条之类的功能)
装货服务:
从'@angular/cdk/Overlay'导入{Overlay,OverlayRef};
从'@angular/cdk/portal'导入{ComponentPortal};
从“@angular/core”导入{Injectable};
从'rxjs'导入{defer,NEVER,Subject};
从“rxjs/operators”导入{finalize,share};
从“../shared/components/loading/loading.component”导入{LoadingComponent};
@可注射({providedIn:'root'})
导出类装入服务{
私有overlayRef?:overlayRef;
isLoading=新主题();
构造函数(私有覆盖:覆盖){}
public show():无效{
this.isLoading.next(true);
Promise.resolve(null)。然后(()=>{
this.overlayRef=this.overlay.create({
位置策略:this.overlay.position().global().center卧式().centervertical(),
哈斯:是的,
});
this.overlayRef.attach(新组件门户(加载组件));
});
}
公共只读微调器$=延迟(()=>{
this.show();
返回NEVER.pipe(finalize(()=>this.hide());
}).pipe(share());
public hide():void{
this.isLoading.next(false);
this.overlayRef!.detach();
this.overlayRef=未定义;
}
}
你能不能把它放在可观察管道的外面/前面?@ChrisYungmann如果我调用一个返回可观察的函数,而不是订阅它,我会得到一个无限装载器