我有一个带有角的壁炉应用程序
"@angular/cdk": "19.0.4",
"@angular/common": "19.0.5",
"@angular/compiler": "19.0.5",
"@angular/core": "19.0.5",
"@angular/fire": "19.0.0",
我也有main.ts
文件,其中包含
import { ApplicationConfig, enableProdMode, importProvidersFrom } from '@angular/core';
import { environment } from './environments/environment';
import { BrowserModule, bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app/app-routing.module';
import { AppComponent } from './app/app.component';
import { provideHttpClient, withInterceptors, withInterceptorsFromDi } from '@angular/common/http';
import { authInterceptor } from './app/interceptors/auth.interceptor';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
if (environment.production) {
enableProdMode();
}
export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom(BrowserModule, AppRoutingModule),
provideAnimations(),
provideHttpClient(withInterceptorsFromDi(), withInterceptors([authInterceptor])),
provideFirebaseApp(() => initializeApp(environment.firebaseConfig)),
provideAuth(() => getAuth())
]
};
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
在我的app.component.ts
我订阅用户更改
private subscribeUserEvents() {
this.authService.user$.subscribe(async (user) => {
if (user) {
this.authService.currentUserSig.set({
id: user.uid,
username: user.displayName,
email: user.email,
token: await user.getIdToken()
});
} else {
this.authService.currentUserSig.set(null);
}
});
}
我也有这样做
auth.service.ts
import { Injectable, signal } from '@angular/core';
import {
Auth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signOut,
setPersistence,
browserLocalPersistence,
user
} from '@angular/fire/auth';
import { Router } from '@angular/router';
export interface User {
id: string;
username: string;
email: string;
token: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private auth: Auth, private router: Router) {
setPersistence(this.auth, browserLocalPersistence).then(() => console.log('Persistence set to browser local'));
}
user$ = user(this.auth);
currentUserSig = signal<User | null | undefined>(undefined);
register(email: string, password: string) {
return createUserWithEmailAndPassword(this.auth, email, password);
}
async login(email: string, password: string) {
return signInWithEmailAndPassword(this.auth, email, password);
}
async logout() {
await signOut(this.auth);
await this.router.navigate(['/sign-in']);
}
}
最后,
auth.guard.ts
import { Injectable, inject } from '@angular/core';
import { CanActivate, Router, UrlTree } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
private authService = inject(AuthService);
private router = inject(Router);
canActivate(): Observable<boolean | UrlTree> {
return this.authService.user$.pipe(
take(1),
map(user => {
if (user) {
return true;
} else {
return this.router.createUrlTree(['/sign-in']);
}
})
);
}
}
似乎一切正常,代币被传递给后端呼叫,轮换受到保护等...但是当我第一次打开应用程序时,我会看到这个错误。我认为这与
auth.interceptor.ts
中的燃烧案提供者有关,但我不知道为什么会发生这种情况
Error TypeError:CLS不是构造函数
在_getInstance(index-dfc2d82f.js:1954:16)
在index-dfc2d82f.js:2839:59
在genertator.next()
在asyncgeneratorStep(asynctogenerator.js:3:1)
在_next(asynctogenerator.js:17:1)
在异步生仪上:22:1
在新的ZoneAwarePromise(Zone.JS:2702:25)
在asynctogenerator.js:14:1
在_zonedelegate.Invoke(Zone.JS:369:28)
在Zoneimpl.run(Zone.JS:111:43)
我也有同样的问题。我将问题调试到
STPERSISTANCE调用。根据这一讨论,呼叫设置持久性的正确方法是通过auth实例方法来调用它:
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const token = authService.currentUserSig()?.token;
if (token) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next(req);
};