Javascript 具有异步回调的表操作
说明 我创建了一个表组件(Javascript 具有异步回调的表操作,javascript,angular,typescript,rxjs,Javascript,Angular,Typescript,Rxjs,说明 我创建了一个表组件(MyTable),并在表中设置了一个名为“Actions”的列 可以对每行执行不同的操作(例如删除、编辑等) 每个表操作都有一些属性:图标、文本和回调函数(callbackFn) 在MyTablecode中,我想通过设置:this.inProgress=true在单击操作按钮时显示微调器 在执行callbackFn之后,我需要设置this.inProgress=false callbackFn可以是一个异步api调用,如下代码所示: myapp.component.ts
MyTable
),并在表中设置了一个名为“Actions”的列
可以对每行执行不同的操作(例如删除、编辑等)
每个表操作都有一些属性:图标、文本和回调函数(callbackFn
)
在MyTable
code中,我想通过设置:this.inProgress=true
在单击操作按钮时显示微调器
在执行callbackFn之后,我需要设置this.inProgress=false
callbackFn
可以是一个异步api调用,如下代码所示:
myapp.component.ts
const tableActions:MyTableActions[]=[
{
图标:“某个图标”,
callbackFn:()=>{
http.post('someapi').subscribe(r=>{
//重要提示:我需要在这里做一些事情{
//执行其他操作的其他回调函数(行上的其他操作)
}
];
const someOtherTableActions:MyTableActions[]=[{/*…*/},{/*…*/}];
myapp.component.html
my-table.component.ts
onAction单击(行){
this.inProgress=true;
callbackFn().subscribe(null,null,()=>{
//完成后,将inProgress设置为false您不需要订阅两次,在第一种情况下-您需要返回cold
observable(或just be andaction
),并且只在组件中订阅
行动中
或“更好”的方式:
p、 如果需要,请进行调整,因为我已在这里的StackOverflow答案框中“开发”:在代码中添加了更多的注释以澄清问题。这样一来,首先这里的inProgress
没有定义。inProgress
只在MyTable.Component.ts中定义。我们在这里初始化的这个callbackn在另一个类/文件/组件中使用。并且没有访问inProgress的权限。我也应该这样做一些其他的t例如,如果有错误,请显示一个snackbar。callback$==callbackFn-我用$cause命名它,因为它是可观察的(不是Fn),并且一切正常-callback$.pipe(finalize(()=>this.inProgress=false)).subscribe();
在我的表.component.ts中使用(您在那里有inProgress)
const tableActions: MyTableActions[] = [
{
icon: 'some icon',
callbackFn: () => {
http.post<any>('some api').subscribe(r => {
// IMPORTANT: I need to do some stuff here <========================
// Note that the code that is here cannot be in the subscribe of the
// onActionClick() in the MyTable component.
// for example I can show a snackbar here and in my second instance
// of table I show some other messages in UI.
// However after this finishes, the code in the Table OnActionClick
// should always set the inProgress to false, AFTER the stuff in
// here is done!
});
}
},
{
icon: 'some other icon',
callbackFn: () => {
// some other callback function that does something else (some other action on the row)
}
];
const someOtherTableActions: MyTablActions[] = [{/*...*/}, {/*...*/}];
<my-table [actions]="tableActions"><my-table>
<my-table [actions]="someOtherTableActions"><my-table>
onActionClick(row) {
this.inProgress = true;
callbackFn().subscribe(null, null, () => {
// on complete, set inProgress to false <==============================
this.inProgress = false;
})
}
callback$: http.post<any>('some api')
callback$.subscribe(null, null, () => {
// on complete, set inProgress to false;
this.inProgress = false;
})
callback$.pipe(finalize(() => this.inProgress = false)).subscribe();