我有如下情况:
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
return of(null);
}
})
).subscribe(myObservable1 | myObservable2) => {
Run Code Online (Sandbox Code Playgroud)
因此,如果条件为假,我只需要执行一个请求,如果条件为真,我必须将第一个请求链接到下一个请求,它们本质上是对服务器 api 的两个请求。
有没有更好的解决方案而不返回它null?
RxJs 中有条件运算符吗?
谢谢!
我很难理解这一点。当我将 switchMap 运算符与 Observable 一起使用时,它会按预期发出所有值:
Observable.from([1, 2, 3, 4, 5])
.do(console.log)
.switchMap(i => Observable.of('*' + i))
.do(console.log)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
结果:
1
*1
2
*2
3
*3
4
*4
5
*5
Run Code Online (Sandbox Code Playgroud)
但是当我用 Promise 替换 Observable 时,我得到了不同的行为:
Observable.from([1, 2, 3, 4, 5])
.do(console.log)
.switchMap(i => new Promise((resolve) => resolve('*' + i)))
.do(console.log)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
结果:
1
2
3
4
5
*5
Run Code Online (Sandbox Code Playgroud) 如果我向服务器发出新的 http 请求,我想取消之前的 http 请求,但它没有按我的预期工作。
如果函数中的某些值发生更改,我想取消请求我的意思是如果值更改旧请求应该取消并且新请求应该为此创建我已经这样做了
1) 创建了一个主题 - 将被监视的东西observable
public stringVar = new Subject<string>();
2)创建一个observable来观察主题并发送更新流(您将订阅此以获取更新流)
public stringVar$ = this.stringVar.asObservable()
Run Code Online (Sandbox Code Playgroud)
3)在特定函数中,我将值作为参数获取,因此我执行这些步骤
testFunction(value){
this.stringVar.next(listValueSelected);
this.testOutput = this.stringVar$.pipe(
switchMap(() => {
return this.teseService.getEntries(val_one, val_two,val_three);
})
)
this.testOutput.subscribe(result => console.log(`${result}`));
}
Run Code Online (Sandbox Code Playgroud)
当值将要更改但第一次只有一个请求是模式时,该请求是可取消的,但是当我第二次单击它时,它会调用 api 两次,这将继续。我的代码有什么问题?
在 component.ts
export class TestComponent {
testOutput :Observable<any>;
stringVar = new Subject<number>();
stringVar$ = this.stringVar.asObservable();
testResult(selectedValue) {
this.stringVar.next(selectedValue);
this.stringVar$.subscribe(data => {
});
this.testOutput = this.stringVar$.pipe(
switchMap(() => {
return this.testService.getTestEntries(this.x,this.y,this.z);
})
)
this.testOutput.subscribe(result => console.log(`${result}`));
}
}
Run Code Online (Sandbox Code Playgroud)
在服务文件中
getTestEntries(x, …Run Code Online (Sandbox Code Playgroud) 在我的项目中,当用户更改另一个列表中的选定值时,我有时希望更新列表中的可用选项。为此,我使用了valueChanges运算符pipe,switchMap如下所示:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return this.typesService.getProjectsByType(typeId);
}),
)
.subscribe((projects) => {
//...
});
Run Code Online (Sandbox Code Playgroud)
现在我遇到的问题是,我需要一次执行两个 http 请求来更新多个列表,而不是仅更新一个列表。当我尝试添加第二个时switchMap,我得到error TS2345: Argument of type 'OperatorFunction<number, Project[]>' is not assignable to parameter of type 'OperatorFunction<any, number>'.以下是我尝试执行此操作的方法:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return this.typesService.getProjectsByType(typeId);
}),
switchMap((typeId: number) => {
return this.typesService.getProgramsByType(typeId);
}),
)
.subscribe(([projects, programs]) => {
//...
});
Run Code Online (Sandbox Code Playgroud)
如何在此处添加第二个 http 请求,以便我可以处理 中两个请求收到的数据subscribe?
每当触发新请求时,我都有一个用例,任何已经在进行中的 http 请求都应该被取消/忽略。
例如:
- 一个请求(比如#2)进来,而请求#1 响应时间太长/网络连接慢。
- 在这种情况下,#2 从服务器获得非常快的响应,然后在任何时候,即使 #1 返回响应,HTTP 响应 observable 也应该被忽略。
- 我面临的问题是,首先组件显示来自请求 #2 的响应值,并在请求 #1 完成时再次更新(这不应该发生)。
我认为 switchMap 取消了 obervables / 维护了发出 observable 值的顺序。
摘自我的 service.ts
Obervable.of('myServiceUrl')
.switchMap(url => this.httpRequest(url) )
.subscribe( response => {
// implementation
/** Update an observable with the
with latest changes from response. this will be
displayed in a component as async */
});
private httpRequest(url) {
return this.httpClient.get('myUrl', { observe: 'response' });
}
Run Code Online (Sandbox Code Playgroud)
上面的实现不起作用。有人能找出这个用例的正确实现吗?
我有一个简单的设置,可以在异步管道为空时显示加载旋转器:
<div *ngIf="(searchResults$ | async) as searchResults; else loading">
</div>
<ng-template #loading>
loading..
</ng-template>
Run Code Online (Sandbox Code Playgroud)
但是,当用户第二次再次搜索时,加载...不显示,我想我需要这个 searchResults$ observable 来发出 null 以再次显示微调器,或者有一个单独的 isLoading 变量。
最好的方法是什么?
如果重要的话,我有一个 debounce 和一个 switchMap (即使用 Finalize 等很棘手)
this.searchResults$ = this.filters$
.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap((f) => {
return httpGet(f)
})
)
Run Code Online (Sandbox Code Playgroud)
另外,我尝试过,*ngIf="!isLoading && (searchResults$ | async) as searchResults但发现它有问题,例如 searchResults$ 未订阅,或者角度抱怨更改检测后的更改
我发送了以下代码片段以供代码审查。此效果需要在请求调用后分派成功操作,或者如果服务方法抛出错误则分派错误操作,因此非常标准。
@Effect()
fetchData$ = this.actions$.pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
)};
));
Run Code Online (Sandbox Code Playgroud)
然而,外部开发人员给了我一条评论(我没有与之联系,因此无法要求澄清)。他指示我用另一个 switchMap 包装我的 switchMap(就像下面的代码),因为我上面的代码中第一个 switchMap 内的捕获错误“会导致效果中断”。
@Effect()
fetchData$ = this.actions$.pipe(
switchMap((a: StoreAction<IType>) => of(a).pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
);
}),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
))
);
Run Code Online (Sandbox Code Playgroud)
现在,我阅读了有关捕获效果中的错误的内容,我的理解是 catchErrors 需要包装在 switchMap 中,因为这样效果就不会中断,因为失败的内部(而不是外部)可观察对象将被成功的可观察对象和效果可观察对象替换最终可以被迫进入成功状态(如果我理解正确的话)。
我不明白和缺少的是:为什么我们要将 switchMap 包装到另一个 switchMap 中?有人可以解释一下第一种情况与第二种情况下这个特定可观察量的工作流程吗?
所以我是 RXJS 的新手。我想要做的是设置一个会话到期计时器,当用户收到他们的会话即将到期的模式提示时,如果他们单击继续,计时器将被重置。
我一直在阅读 switchMap 和 switchMapTo,但我发现的示例使用了某种点击事件或鼠标移动事件。我的情况是,我不想在单击按钮时刷新,因为我正在验证 JWT。成功验证 JWT 后,我将刷新计时器。
我为用户设置了一个公共库,可以像这样设置计时器:
private tick: Subscription;
public tokenExpirationTime: Subject<number>;
setupExpirationTimer():void {
// Start the timer based on the expiration
var expirationSeconds = this.expiration * 60;
this.tick = Observable.timer(0, 1000).map(i => expirationSeconds - i).subscribe(x => {
// Set the seconds in the user object
this.tokenExpirationTime.next(x);
console.log("TIMER: " + x);
});
}
Run Code Online (Sandbox Code Playgroud)
在我的代码的其他地方,我订阅了 tokenExpirationTime(这是我如何知道计时器上的当前时间,所以我知道何时显示我的弹出窗口)。
前任。
this.user.tokenExpirationTime.subscribe(x => { ... });
Run Code Online (Sandbox Code Playgroud)
我可能做错了这一切,因为我是新手。我希望我的解释清楚,但如果没有,请告诉我。感谢您的帮助!
使用 Angular 4,我从 observable 中的 firebase db 获取数组列表。如何将 observable 的类型更改为数组,反之亦然以使其工作?
我写的没有不同的功能。我正在使用一个内置函数 switchMap,在其中分配一个 Products 数组。我无法弄清楚如何将可观察的 switchMap 更改为数组可观察。
constructor(
route:ActivatedRoute,
productService: ProductService ) {
productService
.getAll()
.switchMap(products => {
//getting compile error at below line for this.products
this.products = products;
return route.queryParamMap;
})
.subscribe(params => {
this.category = params.get('category');
this.filteredProducts = (this.category) ?
this.products.filter(p => p.category === this.category) :
this.products;
});
}
Run Code Online (Sandbox Code Playgroud)
switchMap observable 一次返回一项的结果,这里有一个数组列表。我如何使它工作。
return this.auth.user.pipe(
switchMap((user: IUser) => {
return of(true);
})
);
Run Code Online (Sandbox Code Playgroud)
我的初始代码有些复杂,在某些情况下取决于用户数据,但是出于测试目的,我在警卫队的canLoad中使用了上面的代码,并且该代码无法激活。
任何TS /编译错误。
无论是否使用常春藤,我都尝试过。
我正在使用Angular 8.3;
switchmap ×10
rxjs ×9
angular ×8
observable ×5
angular-pipe ×1
angular12 ×1
firebase ×1
http ×1
ngrx ×1
ngrx-effects ×1
promise ×1
rxjs5 ×1
timer ×1