【发布时间】:2018-11-29 18:47:11
【问题描述】:
我决定将我的 Angular5 工作项目升级到 Angular6 并随之升级所有依赖项(例如 rxjs 现在是版本 6 以及 angular-cli)
我遇到了一个似乎无法解决的问题:
ERROR in src/app/services/auth/auth-guard.service.ts(25,14): error TS2339: Property 'take' does not exist on type 'Observable<User>'.
这在以前不是问题。我知道现在我们需要用“管道”包装 rxjs 运算符,虽然我在这里尝试过管道包装器中的嵌入代码仍然会导致类似的问题,所以我决定将损坏的类放在这里:
import { Injectable } from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.currentUser
.take(1)
.map(user => !!user)
.do(signedIn => {
if (!signedIn) {
console.log('access denied');
this.router.navigate(['/signin']);
}
});
}
}
我尝试使用以下方法修复它:
import { take } from 'rxjs/operators';
...
return this.authService.currentUser
.pipe(
take(1)
.map(user => !!user)
.do(signedIn => {
if (!signedIn) {
console.log('access denied');
this.router.navigate(['/signin']);
}
})
);
然后得到“地图不存在”等等。如果我take(1).pipe( 那么我得到管道不存在。
我没有成功地找到合适的答案。
以防万一在AuthService 中设置this.authService.currentUser 看起来像这样(请注意,对于这个我成功地使用pipe 让switchMap 工作):
constructor(
private router: Router,
private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private http: HttpClient,
private headerService: HeaderService
) {
this.authState = this.afAuth.authState;
this.currentUser = this.afAuth.authState
.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
})
);
}
【问题讨论】:
-
在
pipe中使用operators时,不要用.(点)链接它们。相反,你用,(逗号)pipe( take(1), map(...), switchMap(...) )分隔它们 -
非常感谢 - rxjs、打字稿或一般角度的管道部分也是如此?
-
它是
RxJs的一部分。
标签: javascript angular rxjs frontend angularfire2