Help pls, to make it work. isLoggedIn$ = this._isLoggedIn$.asObservable() always false, but when i make login _isLoggedIn$ true
@Injectable({
providedIn: 'root',
})
export class AuthService {
private _isLoggedIn$ = new BehaviorSubject<boolean>(false);
public isLoggedIn$ = this._isLoggedIn$.asObservable();
role: String | null;
constructor(private http: HttpClient) {
}
login(form: FormGroup) {
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.http.post(`${environment.apiBaseUrl}/api/login`, form.getRawValue(), {headers: headers, withCredentials: true}).pipe(
tap((response: any) => {
this._isLoggedIn$.next(true);
this.role = response.role;
})
);
}
}
@Injectable({
providedIn: 'root',
})
export class IsAuthenticatedGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
console.log(this.authService.isLoggedIn$)
return this.authService.isLoggedIn$;
}
}
i tried through this.authService.isLoggedIn$.pipe(tap( but nothing, what i do wrong?
When you use Observables as a return value of Guards, those Observables should complete. This is not the case in your example, since your using a Subject as a source.
To solve it you could use either first()
operator
return this.authService.isLoggedIn$.pipe(first());
Or take(1)
return this.authService.isLoggedIn$.pipe(take(1));
You can read more about it in the docs here
cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.