Angular 和 RXJS - [ts] 属性'map'在类型 'Observable<User>' 上不存在



自从创建一个新的 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:Activated RouteSnapshot, 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)
)
}

我认为您使用了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)
)
}
}

请注意您现在如何导入运算符以及如何将maptake放入pipe方法中。

相关内容

最新更新