自创建一个新的angular 6项目以来,我之前复制过的某些先前代码似乎无法正常工作。这似乎主要是rxjs语法
在 .map 上,显示错误:
[ts] Property 'map' does not exist on type 'Observable'<User>'.
我似乎在另一个带有 .take
的文件上遇到了类似的错误有人能指出正确的方向来解决这个问题吗?
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/do';
@Injectable()
export class LoginGuardService implements CanActivate {
constructor(
private router: Router,
private auth: AngularFireAuth
) { }
canActivate(): Observable<boolean> {
return this.auth.authState.map(authState => {
if (authState) this.router.navigate(['/folders']);
return !authState;
}).take(1);
}
}
第二卫兵
canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot):
Observable<boolean> {
this.authGuardStateURL = state.url;
return this.auth.authState.pipe(
take(1)
.map(authState => !!authState)
.do(auth => !auth ? this.router.navigate(['/login']) : true)
)
}
答案 0 :(得分:1)
我认为您使用Angular CLI创建了您的应用程序。 Angular 6随RxJS 6一起提供,并且从v5开始,RxJS一直在使用可管道运算符。
因此您的代码应如下所示:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import { map, take, tap } from 'rxjs/operators';
@Injectable()
export class LoginGuardService implements CanActivate {
constructor(
private router: Router,
private auth: AngularFireAuth
) { }
canActivate(): Observable<boolean> {
return this.auth.authState.pipe(
map(authState => {
if (authState) this.router.navigate(['/folders']);
return !authState;
}),
take(1)
)
}
//Second Guard
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot): Observable<boolean> {
this.authGuardStateURL = state.url;
return this.auth.authState.pipe(
take(1),
map(authState => !!authState),
tap(auth => !auth ? this.router.navigate(['/login']) : true)
)
}
}
注意现在如何导入运算符,以及如何将map
和take
放入pipe
方法中。