take(1)与first() [英] take(1) vs first()
问题描述
我发现了一些使用take(1)
的AuthGuard
的实现.在我的项目中,我使用了first()
.
I found a few implementation of AuthGuard
s that use take(1)
. In my project, I used first()
.
两者的工作方式相同吗?
Do both work the same way?
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFire } from 'angularfire2';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private angularFire: AngularFire, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.angularFire.auth.map(
(auth) => {
if (auth) {
this.router.navigate(['/dashboard']);
return false;
} else {
return true;
}
}
).first(); // Just change this to .take(1)
}
}
推荐答案
运算符first()
和take(1)
不同.
first()
运算符采用可选的predicate
函数,并在源完成时没有值匹配时发出error
通知.
The first()
operator takes an optional predicate
function and emits an error
notification when no value matched when the source completed.
例如,这将发出错误:
import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
...以及此:
range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
这将与发出的第一个值匹配:
While this will match the first value emitted:
range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
另一方面,take(1)
仅采用第一个值并完成.无需进一步的逻辑.
On the other hand take(1)
just takes the first value and completes. No further logic is involved.
range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
然后使用可观察到的空源它将不会发出任何错误:
Then with empty source Observable it won't emit any error:
EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
2019年1月:已针对RxJS 6更新
Jan 2019: Updated for RxJS 6
这篇关于take(1)与first()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!