Comments (9)
Hi, your code doesn't reproduce the issue. Could you try to provide a reproduction on stackblitz ?
Also is your Guard comming from a library ?
from angular.
Hi, your code doesn't reproduce the issue. Could you try to provide a reproduction on stackblitz ?
Also is your Guard comming from a library ?
Not. It's the functional version of the framework's native guard.
The project is very large, I encountered this error after upgrading angular to the latest version and integrating the new features offered such as standalone components. Please try checking here first for errors:
app.config.ts
const RETRY_INTERCEPTOR_CONFIG: RetryConfig = { count: 3, delay: 1000 };
const checkForUpdates = async (swUpdate: SwUpdate) => {
try {
// Check if running in Browser
if (!isPlatformBrowser(inject(PLATFORM_ID))) return;
// Check if Service Worker is supported by the Browser
if (!swUpdate.isEnabled) return;
// Check if new version is available
const isNewVersion = await swUpdate.checkForUpdate();
if (!isNewVersion) return;
// Check if new version is activated
const isNewVersionActivated = await swUpdate.activateUpdate();
// Reload the application with new version if new version is activated
if (isNewVersionActivated) window.location.reload();
} catch (error) {
console.log('Service Worker - Error when checking for new version of the application:', error);
window.location.reload();
}
};
export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom([
CalendarModule.forRoot({ provide: DateAdapter, useFactory: adapterFactory })
]),
provideLocaleConfig(),
provideCharts(withDefaultRegisterables()),
provideRouter(
routes,
withComponentInputBinding(),
withDebugTracing(),
withInMemoryScrolling({
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled'
}),
withDisabledInitialNavigation(),
withEnabledBlockingInitialNavigation(),
withPreloading(PreloadAllModules),
withRouterConfig({ onSameUrlNavigation: 'reload' }),
withViewTransitions({ skipInitialTransition: true }),
withPreloading(PreloadAllModules),
withDebugTracing()
),
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:10000'
}),
provideHttpClient(
withFetch(),
withInterceptors([
authInterceptor,
errorInterceptor,
loaderInterceptor,
retryInterceptor(RETRY_INTERCEPTOR_CONFIG)
]),
withJsonpSupport(),
withXsrfConfiguration({ cookieName: 'TOKEN', headerName: 'X-TOKEN' })
),
provideAnimations(),
provideClientHydration(withHttpTransferCacheOptions({ includePostRequests: true })),
{ provide: APP_ID, useValue: 'serverApp' },
{ provide: APP_BASE_HREF, useValue: '/app' },
{
provide: APP_INITIALIZER,
multi: true,
deps: [SwUpdate, AppConfigService],
useFactory: (swUpdate: SwUpdate, appConfigService: AppConfigService) => {
return async () => {
const config = await appConfigService.loadAppConfig();
checkForUpdates(swUpdate);
return config;
};
}
},
{
provide: IMAGE_CONFIG,
useValue: {
disableImageSizeWarning: false,
disableImageLazyLoadWarning: false
}
},
{ provide: LocationStrategy, useClass: PathLocationStrategy }
]
};
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
schemas: [CUSTOM_ELEMENTS_SCHEMA],
styleUrls: ['./app.component.scss'],
standalone: true,
imports: [
CommonModule,
MaterialModule,
BrowserModule,
BrowserAnimationsModule,
NgxTranslateModule,
TransferHttpCacheModule,
RouterOutlet
],
providers: []
})
export class AppComponent implements OnInit {
title = '...';
constructor(
private readonly dateAdapter: DateCoreAdapter<Date>,
private readonly localeService: LocaleService,
private readonly translate: TranslateService,
private readonly iconService: IconService,
private readonly faLibrary: FaIconLibrary,
private readonly faConfig: FaConfig
) {
this.translate.addLangs(['en', 'it']);
this.useLanguage('it');
this.notificationBackground();
const browserLang: any = translate.getBrowserLang();
this.translate.use(browserLang && /en|it/.test(browserLang) ? browserLang : 'it');
}
ngOnInit() {
moment.locale(this.localeService.defaultLocale(), {
week: { dow: 1, doy: 4 }
});
registerLocaleData(locale);
findLocation(this.environment);
this.faConfig.fixedWidth = true;
this.faLibrary.addIcons(
faFilePdf,
faFileExcel,
faServer,
faCode,
faUserShield,
faShare,
farFilePdf,
farFileExcel
);
this.iconService.registerAll(appIcons);
}
public default() {
this.dateAdapter.setLocale(this.localeService.getCurrentLocale());
}
private useLanguage(language: string) {
this.translate.setTranslation(language, defaultLanguage);
this.translate.setDefaultLang(language);
this.translate.use(language);
}
private environment(location: string | null) {
console.group('π Variabili ambiente');
console.log(`1. π³οΈβπ Lingua browser: ${this.localeService.defaultLocale()}`);
console.log(`2. π³οΈβπ Lingua applicazione: ${moment.locale()}`);
console.log(`3. π Tema notturno: ${isDarkMode() ? 'β
' : 'βοΈ'}`);
console.log(`4. π Connessione rete: ${window.navigator.onLine ? 'β' : 'βοΈ'}`);
console.log(`5. π§ Posizione corrente: ${location ?? 'n.d.'}`);
console.groupEnd();
}
private notificationBackground() {
let notification: any;
let interval: any;
fromVisibilityChange().subscribe(res => {
if (document.visibilityState === 'hidden') {
const leaveDate = new Date();
interval = setInterval(() => {
notification = new Notification(this.title, {
body: `In modalitΓ background da ${Math.round(
(Date.now() - leaveDate.getTime()) / 1000
)} secondi.`,
tag: 'Torna Indietro'
});
}, 100);
} else {
if (interval) clearInterval(interval);
if (notification) notification.close();
}
});
}
}
app.config.server.ts
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering()]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
main.ts
if (environment.production) enableProdMode();
bootstrapApplication(AppComponent, appConfig).catch(e => console.error(e));
from angular.
At least checkForUpdates
is using inject
while being called from inside a useFactory
callback after an await point, so checkForUpdates
doesn't run in an injection context there (everything after the await
executes in a microtick in a new stack). There's likely a similar thing going on in your CanActivateFn
callback.
from angular.
At least
checkForUpdates
is usinginject
while being called from inside auseFactory
callback after an await point, socheckForUpdates
doesn't run in an injection context there (everything after theawait
executes in a microtick in a new stack). There's likely a similar thing going on in yourCanActivateFn
callback.
The object relative to APP_INITIALIZER was commented but error continues. if you tell me what I can comment or change.
The non-functional guard encounters the same problem.
{
path: '',
resolve: {},
canActivate: [AuthenticationGuard],
component: NavigationComponent,
children: [...]
}
@Injectable({
providedIn: 'root'
})
export class AuthenticationGuard implements CanActivate {
constructor(
private readonly authenticationService: AuthenticationService,
private readonly globalService: GlobalService,
private readonly router: Router
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const authentication = this.authenticationService.getAuthentication();
if (!authentication || FunctionDates.lessNow(authentication.dataScadenza)) {
this.globalService.clear();
this.router.navigateByUrl('/login');
}
return !!authentication; // eslint-disable-line
}
}
from angular.
I won't be able to help further without runnable reproduction.
from angular.
Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on StackOverflow using tag angular
.
If you are wondering why we don't resolve support issues via the issue tracker, please check out this explanation.
from angular.
I add project on stackblitz.
from angular.
It's the same as in angular/angular-cli#27122. The path mapping for @angular
causes @angular/core
to be included multiple times during ng serve
(with the Vite devserver), each having their own, independent, injection context.
from angular.
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.
from angular.
Related Issues (20)
- Angular 17 @for has memory leak HOT 1
- Reactive forms directives should be standalone HOT 1
- Rename Change detection "Default"
- `swPush.requestSubscription` never resolves on Arc browser (mac os) HOT 1
- AngularGPT
- Recursive template with @defer HOT 3
- The output-function page is not accessible https://angular.dev/guide/output-function
- developer preview features HOT 2
- toSignal causes the signal to not being lazy-evaluated HOT 6
- API for ngModule bootstrap for SSR? - `platformServer.bootstrapModule` vs `bootstrapApplication` of `@angular/platform-server`? HOT 2
- Renderer2 method that allows you to set signal inputs HOT 5
- Angular attributes produce HTML validation errors HOT 3
- Angular 15 - router.events are empty with nested router outlets on page refresh HOT 1
- The CSP nonce remains in the DOM after being read by Angular HOT 1
- API Reference search on angular.dev HOT 3
- Improve the angular.dev dark mode HOT 1
- Use hadError instead of errors
- docs: @defer requires the parent component also be standalone
- BrowserViewportScroller not honoring native scroll margin HOT 4
- Unit Testing guide has incorrect code HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from angular.