我正在尝试为用户创建一个授权系统。我正在使用 Angular11。我对 angular 完全陌生。我在我的代码中也返回了一个布尔类型。但是,我还是发现了一个错误。
这是我的代码如下:-
auth.guard.ts
(这里是主要问题)
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AccountService } from '../_services/account.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private accountService : AccountService, private toastr : ToastrService){}
canActivate(): Observable<boolean> {
return this.accountService.currentUser$.pipe(
map(user => {
if(user) return true;
this.toastr.error(error);
})
)
}
}
account.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../_models/user';
@Injectable({
providedIn: 'root'
})
export class AccountService {
baseUrl='https://localhost:5001/api/';
private currentUserSource =new ReplaySubject<User> (1);
currentUser$=this.currentUserSource.asObservable();
constructor(private http :HttpClient) { }
login(model:any)
{
return this.http.post<User>(this.baseUrl+'account/login',model).pipe(
map((response:User)=>{
const user=response;
if(user){
localStorage.setItem('user',JSON.stringify(user));
this.currentUserSource.next(user);
}
})
)
}
register(model:any)
{
return this.http.post<User>(this.baseUrl +'account/register',model).pipe(
map((user:User)=>{
if(user){
localStorage.setItem('user',JSON.stringify(user));
this.currentUserSource.next(user);
}
return user;
})
)
}
setCurrentUser(user:User)
{
this.currentUserSource.next(user);
}
logout()
{
localStorage.removeItem('user');
this.currentUserSource.next(null as any);
}
}
我的错误是:-
为什么错误我不明白。我如何解决这个问题。请帮忙。
答案 0 :(得分:3)
错误表明 canActivate 方法返回的不是 Observable
因此,让我们检查您的地图管道以了解为什么会出现这种情况:
map(user => {
// we only return here so
// only true is possible to be returned
if(user) return true;
// after this line nothing will be returned so the observable can only return true | undefinded
this.toastr.error(error);
})
您可以通过确保始终返回这样的 bool 值来解决此问题
map(user => {
if(user) return true;
this.toastr.error(error);
// this line bellow is new it changes the return type from true | undefined into boolean
return false;
})
答案 1 :(得分:0)
您需要返回 observable 而不仅仅是布尔值:
import { of, Observable } from 'rxjs';
canActivate(): Observable<boolean> {
return this.accountService.currentUser$.pipe(
map(user => {
if(user) {
return of(true);
}
this.toastr.error(error);
})
)
}
如果您使用的是 rxjs6 则将以上内容修改为:
import { of as observableOf, Observable } from 'rxjs';
canActivate(): Observable<boolean> {
return this.accountService.currentUser$.pipe(
map(user => {
if(user) {
return observableOf(true);
}
this.toastr.error(error);
})
)
}