Coder Social home page Coder Social logo

Comments (9)

JeanMeche avatar JeanMeche commented on April 28, 2024

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.

tonia211262 avatar tonia211262 commented on April 28, 2024

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.

JoostK avatar JoostK commented on April 28, 2024

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.

tonia211262 avatar tonia211262 commented on April 28, 2024

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.

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.

JoostK avatar JoostK commented on April 28, 2024

I won't be able to help further without runnable reproduction.

from angular.

atscott avatar atscott commented on April 28, 2024

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.

tonia211262 avatar tonia211262 commented on April 28, 2024

I add project on stackblitz.

from angular.

JoostK avatar JoostK commented on April 28, 2024

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.

angular-automatic-lock-bot avatar angular-automatic-lock-bot commented on April 28, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.