mteb/FreshStackRetrieval huggingface dataset:
I want to implement AuthGuard using CanActivateFn in Angular 16 which should prevent to view some pages for unauthorized users.
isUserLoggedIn method in UserService is a get request to the backend which returns a loggedin user or throws UNAUTHORIZED exception.
I want to call isUserLoggedIn in AuthGuard and check if it throws UNAUTHORIZED exception then redirect to "/unauth" path otherwise it should return true and do nothing.
The problem: isUserLoggedIn returns Observable<AuthorizedUser> and CanActivateFn needs type boolean. Is there any way to do this without changing the actual GET request in backend ?
@Injectable({providedIn: 'root'})
export class UserService {

 isUserLoggedIn(): Observable<AuthorizedUser> {
   const headers = new HttpHeaders({'Content-Type': 'application/json'});
   return this.apiHandlerService.get<AuthorizedUser>(API_URL, headers);
 }
}

import {CanActivateFn, Router,} from '@angular/router';
import {inject} from '@angular/core';
import {catchError, map, of} from "rxjs";

export const AuthGuard: CanActivateFn = (route, state) => {
    const authService: UserService = inject(UserService);
    const router: Router = inject(Router);

    return authService.isUserLoggedIn().pipe(
        map(response => {
            console.log('Response ', response);
            return true;
        }),
        catchError(error => {
            router.navigate(['/unauthorized'])
            return of(false);
        })
    )
}
I am running Angular 17 projects with standalone components.
I want to add a service where i will start and stop the ngx-ui-loader (
https://www.npmjs.com/package/ngx-ui-loader).
I can't do normal module where i will provide in root ngxui loader like in older versions, so i am wondering if this can work in Angular17?
When loader is directly called and imported in a standalone component it works.
Current implementation is not working..
Service code:
import { Injectable, inject } from '@angular/core';
import { NgxUiLoaderService } from 'ngx-ui-loader';

@Injectable({
  providedIn: 'root',
})
export class LoaderService {
//   ngxLoader = inject(NgxUiLoaderService);
  ngxLoader = inject(NgxUiLoaderService);

  startLoader() {
    console.error('start');
    console.error(this.ngxLoader);
    this.ngxLoader.start();
  }

  stopLoader() {
    this.ngxLoader.stop();
  }


  loaderConfig =
  {
    "bgsColor": "red",
    "bgsOpacity": 0.5,
    "bgsPosition": "bottom-right",
    "bgsSize": 60,
    "bgsType": "ball-spin-clockwise",
    "blur": 5,
    "delay": 0,
    "fastFadeOut": true,
    "fgsColor": "red",
    "fgsPosition": "center-center",
    "fgsSize": 60,
    "fgsType": "ball-spin-clockwise",
    "gap": 24,
    "logoPosition": "center-center",
    "logoSize": 120,
    "logoUrl": "",
    "masterLoaderId": "master",
    "overlayBorderRadius": "0",
    "overlayColor": "rgba(40, 40, 40, 0.8)",
    "pbColor": "red",
    "pbDirection": "ltr",
    "pbThickness": 3,
    "hasProgressBar": true,
    "text": "",
    "textColor": "#FFFFFF",
    "textPosition": "center-center",
    "maxTime": -1,
    "minTime": 300
  }
}

AppComponent.ts


`import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NavbarComponent } from './components/navbar/navbar.component';
import { NgxUiLoaderModule, NgxUiLoaderService } from 'ngx-ui-loader';
import { LoginComponent } from './components/login/login.component';
import { UserService } from './services/user.service';
import { StorageService } from './services/storage.service';
import { finalize, first } from 'rxjs';
import { LoaderService } from './services/loader.service';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  imports: [CommonModule, NavbarComponent, NgxUiLoaderModule, LoginComponent],
})
export class AppComponent {
  title = 'CinAppClient';
  userService = inject(UserService);
  storageService = inject(StorageService);
  ngxLoaderService = inject(NgxUiLoaderService);
  loaderService = inject(LoaderService);

  user$ = this.userService.user$;
  constructor() {}

  ngOnInit() {
    this.loaderService.startLoader();
    let storageUser = this.storageService.getUser();
    if (storageUser !== null) {
      this.userService.authToken = storageUser.token;
      this.userService
        .refreshToken()
        .pipe(
          first(),
          finalize(() => this.loaderService.stopLoader())
        )
        .subscribe();
    }
  }
}
type here

appComponent.html
<ngx-ui-loader [bgsType]="'three-strings'" [fgsType]="'three-strings'">
</ngx-ui-loader>`
type here
Angular v17 onwards defaults to the Standalone approach in the CLI, and there's no more explicit use of @NgModule for application organization. My question is regarding lazy loading with the new default configuration.
Suppose I define my routes in the following way (as im using standalone components):
export const routes: Routes = [
    {'path' : '', component: DashboardComponent},
    {'path' : 'users', component: UsersComponent},
    {'path' : '**', component: DashboardComponent},
];


Will lazy loading still work with this new standalone-oriented approach, or is it necessary to adhere to the traditional @NgModule and feature module way to apply the lazy loading concept in Angular v17? I'd appreciate any insights, experiences, or documentation references related to this potential change in behavior.
I have this code
this.items.mutate(products => this.sourceData.getData().forEach(item => products.push(item)));

updating the library from Angular 16 to Angular 17 I need to remove 'mutate' using 'update' or 'set', but I don't know how to do it.
I should change products.push(item)-> [...products, item] but I don't know how to do it with the forEach.
I am encountering an issue with my Angular 17 SSR (Server-Side Rendering) application. I am using ApexCharts/ng-apexcharts, which currently only works on the browser side. The specific error message I'm facing is:

I understand that this error is expected in an SSR environment, and disabling SSR resolves the issue. However, I am looking for a more robust solution. After some research, I came across the afterNextRender() function, which seems promising.
I am seeking guidance on how to implement afterNextRender() to handle this situation in an Angular 17 SSR application. I believe this could be a valuable workaround, but I'm struggling with the implementation.
Any help or suggestions would be greatly appreciated. Thank you in advance for your assistance!
ps : the chart is displayed but ReferenceError: window is not defined in the terminal is annoying it occurs everytime i import ApexCharts
Here's my current code snippet:
my dashboard.component.ts :
import { AfterRenderPhase, Component, ElementRef, OnInit, ViewChild, afterNextRender } from '@angular/core';
import ApexCharts from 'apexcharts';
import {
  ApexAxisChartSeries,
  ApexChart,
  ApexDataLabels,
  ApexLegend,
  ApexStroke,
  ApexTitleSubtitle,
  ApexXAxis,
  ApexYAxis,
} from 'ng-apexcharts';
export type ChartOptions = {
  series: ApexAxisChartSeries;
  chart: ApexChart;
  xaxis: ApexXAxis;
  stroke: ApexStroke;
  dataLabels: ApexDataLabels;
  yaxis: ApexYAxis;
  title: ApexTitleSubtitle;
  labels: string[];
  legend: ApexLegend;
  subtitle: ApexTitleSubtitle;
};
export const series = {
  // dummy data from apex docs
};
@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.scss'
})
export class DashboardComponent implements OnInit {
  @ViewChild('chart') chart!: ElementRef;
  public chartOptions!: Partial<ChartOptions>;

  constructor() {
    // im struggling here
    afterNextRender(() => {
      const element = this.chart.nativeElement;
      var chart = new ApexCharts(element, this.chartOptions);
      chart.render()
    }, {phase: AfterRenderPhase.Read});
  }
 

  ngOnInit(): void {
    this.chartOptions = {
      series: [
        {
          name: 'STOCK ABC',
          data: series.monthDataSeries1.prices,
        },
      ],
      // chart options config from apex docs
    };
  }
}


in my dashboard.component.html
<div #chart  id="chart"> </div>
Issue
I'm working with an Angular v17 app configured in standalone mode, experiencing issues integrating with Keycloak libraries. Specifically, Keycloak isn't automatically appending the authorization header to backend requests. For security reasons, I prefer not to manually handle the Authorization Token.

I installed Keycloak libs "npm install keycloak-angular"
I added a provider for the Keycloak init
I added some test code to signin and execute a request

All this code is working well with Angular non standalone (NgModule). But since I switched to standalone in angular 17, something is fishy.
To test my code, I have configured an Interceptor: authInterceptorProvider. That is adding the Token manually to each request. Works well. But I don't want to handle tokens by hand...
What might I be missing or configuring wrong?
Code bits (image upload is not working at the moment)
Here my simplyfied Application config
  export const initializeKeycloak = (keycloak: KeycloakService) => {
return () =>
  keycloak.init({
    config: {
      url: 'http://localhost:8180/',
      realm: 'balbliblub-realm',
      clientId: 'blabliblubi-public-client',
    },
    initOptions: {
      pkceMethod: 'S256',
      redirectUri: 'http://localhost:4200/dashboard',
    },
    loadUserProfileAtStartUp: false
  });}


export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes),
  provideHttpClient(
    withFetch(),
    withXsrfConfiguration(
    {
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-XSRF-TOKEN',
    })
  ),

  authInterceptorProvider,
  importProvidersFrom(HttpClientModule, KeycloakBearerInterceptor),
  {
    provide: APP_INITIALIZER,
    useFactory: initializeKeycloak,
    multi: true,
    deps: [KeycloakService],
  },
  KeycloakService,
]};

Here my AppComponent
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
  title = 'testy';
  public isLoggedIn = false;
  public userProfile: KeycloakProfile | null = null;

  constructor(private readonly keycloak: KeycloakService,
              private http: HttpClient) { }

  public async ngOnInit() {
    this.isLoggedIn = await this.keycloak.isLoggedIn();

    if (this.isLoggedIn) {
      this.userProfile = await this.keycloak.loadUserProfile();
    }
  }

  login() {
    this.keycloak.login();
  }

  protected loadAbos() {
    this.http.get<Abo[]>('http://localhost:8080/api/abos?email=' + this.userProfile?.email, { observe: 'response',withCredentials: true })
      .pipe(
        catchError(err => this.handleError("Could not load abos", err)),
        /// if no error occurs we receive the abos
        tap(abos => {
          console.info("loaded abos", abos);
        })
      ).subscribe()
  }

Thanks 4 your help <3
Working with Angular15.
Create a lazy loading modules
app-routing.module.ts
    const routes: Routes = [
      { path: '', redirectTo: '/dashboard', patchMatch: 'full' },
      { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) },
      { path: 'module1', loadChildren: () => import('./module1/module1.module').then(m => m.FirstModule) },
      { path: 'module2', loadChildren: () => import('./module2/module2.module').then(m => m.SecondModule) },
      { path: 'module3', loadChildren: () => import('./module3/module3.module').then(m => m.ThirdModule) },
      { path: 'module4', loadChildren: () => import('./module4/module4.module').then(m => m.FourthModule) },
    ];

@NgModule({
imports: [RouterModule.forChild(routes, {useHash:true})]
exports: [RouterModule]
})
export class AppRoutingModule {}

dashboard.module.ts -- Having components dependency with FirstModule, SecondModule, ThirdModule and FourthModule
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent},
];

@NgModule({
declarations: [DashboardComponent, DashboardDetailsComponent]
imports: [RouterModule.forChild(routes), FirstModule, SecondModule, ThirdModule, FourthModule]
exports: [RouterModule],
bootstrap: [DashboardComponent]
})
export class DashboardModule {}

module1.module.ts  -- Having components dependency with SecondModule and ThirdModule
const routes: Routes = [
  { path: 'module1', component: Module1Component},
  { path: 'module1/details', component: Module1DetailsComponent},
];

@NgModule({
declarations: [Module1Component, Module1DetailsComponent]
imports: [RouterModule.forChild(routes), SecondModule, ThirdModule]
exports: [RouterModule],
bootstrap: [Module1Component]
})
export class FirstModule {}

module2.module.ts  -- Having components dependency with ThirdModule
const routes: Routes = [
  { path: 'module2', component: Module2Component},
  { path: 'module2/details', component: Module2DetailsComponent},
];

@NgModule({
declarations: [Module2Component, Module2DetailsComponent]
imports: [RouterModule.forChild(routes), ThirdModule]
exports: [RouterModule],
bootstrap: [Module2Component]
})
export class SecondModule {}

With the above code getting error
Error: NG04007: The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector. Lazy load modules hould use RouterModule.forChild instead
Its working fine only if DashboardModule is explicitly imported in AppRoutingModule
I have an Angular service that successfully stores the key and value but fails to retrieve it.  Below is the code:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class StorageService {
  constructor() {}

  // Store the value - (Note: This code works fine.  The key is userData and it stores an array of user credentials as value )

  async store(storageKey: string, value: any) {
    localStorage.setItem('key', storageKey);
    localStorage.setItem('value', value);
  }
  
  // Get the value - Here I provide the userData as key but I get a null value.  If put key in "key" then I get an error.  I have verified with console.log(key) that accurate key is passed to retrieve the value.

  async get(key: string) {
    const ret = localStorage.getItem(key);
    return JSON.parse(ret);
  } 
}
I updated my projecto Angular 17.1 and now when i try ng build it creates a server.mjs file in /dist//server directory which is meant to be served for production. when I try to run the file with node or pm2 i get the following error
TypeError: Nl is not a function
    at $C (file:///Users/goldenfox/Projects/front/dist/karlancer/server/server.mjs:106:5771)
    at GC (file:///Users/goldenfox/Projects/front/dist/karlancer/server/server.mjs:106:6227)
    at file:///Users/goldenfox/Projects/front/dist/karlancer/server/server.mjs:106:6318
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)

Node.js v20.11.0

Any Idea about how I can fix this ?
I want to display items of an array of strings from index 1.
arr = [ "str1", "str2", "str3", "str4", "str5" ]

Output should be:
str2
str3
str4
str5

Print all except first one, using new @for loop in angular.
In my Statistics module I got a signal that defines the type of the charts that should appear and this signal is updated using a radio button group.
The signal: typeSignal = signal<string>('OIA')
The radio buttons that sets the :
<div class="btn-group w-auto" role="group">
     @for (type of types; track $index) {
            <input type="radio" class="btn-check" name="btnradio" [id]="type" autocomplete="off"
                [checked]="type==typeSignal()">
            <label class="btn btn-primary" for="btnradio1" (click)="typeSignal.set(type)">{{type}}</label>
     }
</div>

However, I got another computed signal that creates the charts data according to the type signal. Here's the charts signal:
  charts = computed(() => {
    const chartsArr:ChartData[] = []
   if (this.typeSignal() == "OIA") {

      chartsArr.push(this.createBarChart("Status of Incident", ['Closed', 'Ongoing'], "status", "Advisories", true))
      chartsArr.push(this.createBarChart("Severity of Incident", ['Severity 0', 'Severity 1', 'Severity 2', 'Severity 3', 'Severity 4'], "impacts", "Advisories", false))
      chartsArr.push(this.createDonutChart("Communication type", ['Incident', 'Change'], 300))

    } else if (this.typeSignal() == "Portail de l'information") {

      chartsArr.push(this.createBarChart("Status of Incident", ['Scheduled', 'Archived', 'Ongoing'], "status", "Advisories", true))
      chartsArr.push(this.createBarChart("Impact of Incident", ['Major', 'Minor', 'Grave'], "impacts", "Advisories", false))
      chartsArr.push(this.createDonutChart("Communication type", ['Incident', 'Change'], 300))

    } else if (this.typeSignal() == "Bulletin Board") {
      chartsArr.push(this.createBarChart("Status of Change", ['Closed', 'Ongoing', 'Scheduled'], "status", "Advisories", true))
      chartsArr.push(this.createBarChart("Outage of Incident", ['Complete Outage', 'Partial Outage', 'Info'], "impacts", "Advisories", false))
      chartsArr.push(this.createDonutChart("Communication type", ['Info', 'Incident', 'Change'], 300))
    }
    console.log(chartsArr);
    return structuredClone(chartsArr)
  })

and I read this charts signal in my template
@if (["OIA","Portail de l'information","Bulletin Board"].includes(typeSignal())) {
<div class="row row-cols-2 g-5 mx-1">
    @for (chart of charts(); track $index) {
    @if (chart.type == "bar") {
    <app-bar-chart [title]="chart.title" [axissLabels]="chart.labels" [values]="chart.values"
        [valuesType]="chart.valuesType!" [isHorizontal]="chart.isHorizontal!"></app-bar-chart>
    }@else if (chart.type=="donut") {
    <app-donut-chart [title]="chart.title" [values]="chart.values" [labels]="chart.labels"
        [minWidth]="chart.minWidth!"></app-donut-chart>
    }
    }

</div>
}

The problem here is that the charts signal doesn't update the for loop although the console.log(chartsArr); inside it gets logged whenever I toggle the radio buttons.
I migrated to angular 17.1. When I ran the app, I noticed error information about using fetch with httpClient for SSR.
NG02801: Angular detected that `HttpClient` is not configured to use `fetch` APIs. It's strongly recommended to enable `fetch` for applications that use Server-Side Rendering for better performance and compatibility. To enable `fetch`, add the `withFetch()` to the `provideHttpClient()` call at the root of the application.

Application is not bootstrap by standalone component but I found only tutorials for that kind of apps. I put provideHttpClient(withFetch()), to app.server.module.ts and error disappeared.
Im not sure if it is a correct solution for application bootstraped by AppModule. Do you have better options?
I have this new angular signal variables on my component:
private employees: Signal<Employee[]> = this.employeesService.filteredEmployeesSignal;
public employeesDataSource = computed(
    () => new MatTableDataSource<Employee>(this.employees())
);

All works fine until tests fails with this error:
this.employees is not a function
when tries to access to this.employees() signal value. It detects as a function instead as a signal value getter.
I tried to get the value in other local constant inside the computed signal but the error persist.
As you know in angular 17 we can have different syntax for ngIf, ngFor and so on. Am looking for an efficient way of migrating old syntax in html files to the new on presented in Angular 17:
For example I had this old html in angular 15:
<ng-container *ngIf="!dynamicWidth; else FlexibleRef">
  <div class="c-title"></div>
  <div class="c-desc c-desc__short"></div>
  <div class="c-desc c-desc__long"></div>
</ng-container>

<ng-template #FlexibleRef>
  <div
    *ngFor="let item of count | numberRange; let i = index"
    [ngStyle]="{ width: (100 / count) * (i + 1) + '%' }"
    class="flexible-desc"></div>
</ng-template>

And need it in the new syntax like this:
@if (!dynamicWidth) {
  <div class="c-title"></div>
  <div class="c-desc c-desc__short"></div>
  <div class="c-desc c-desc__long"></div>
} @else { 
    @for (item of count | numberRange; track item; let i = $index) {
      <div [ngStyle]="{ width: (100 / count) * (i + 1) + '%' }" class="flexible-desc">. </div>
   } 
}
How can I define the index variable in @for in Angular 17
const users = [
    { id: 1, name: 'Ali' },
    { id: 2, name: 'reza' },
    { id: 3, name: 'jack' },
  ];

<ul>
  @for (user of users; track user.id; let i = index) {
  <li>{{ user.name + i }}</li>
  } @empty {
  <span>Empty list of users</span>
  }
</ul>

index is not known as we had in *ngFor and got Unknown "let" parameter variable "index" in Angular17 @for
But the following is working:
<ul>
  <li *ngFor="let user of users; let i = index">{{ user.name + i }}</li>
</ul>
I've been trying to add "toastr" to my Angular17 project but injecting it into my components does not work. I added it using AngularCLI.
I'm getting the next error:
ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_PDSLoginComponent])[InjectionToken ToastConfig -> InjectionToken ToastConfig -> InjectionToken ToastCo
nfig -> InjectionToken ToastConfig]:
NullInjectorError: No provider for InjectionToken ToastConfig!
Here's what my code contains:
import { Component, Output, EventEmitter, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { ToastrService, ToastNoAnimation } from 'ngx-toastr';

@Component({
  selector: 'app-pdslogin',
  standalone: true,
  imports: [
    FormsModule
  ],
  providers: [
    { provide: ToastrService, useClass: ToastrService },
    { provide: ToastNoAnimation, useClass: ToastNoAnimation }
  ],
  templateUrl: './pdslogin.component.html',
  styleUrls: ['./pdslogin.component.css']
})
export class PDSLoginComponent {
  loginData = {
    UserId: ''
  };
  @Output() loginEvent = new EventEmitter();
  onLogin() {
    this.loginEvent.emit(this.loginData);
    this.toastr.info("SHOWING TOASTR!!!","Info");
  }
  constructor(private router: Router, private toastr: ToastrService) { }
}


I have tried searching for a solution in forums and questions here in Stack Overflow but all of them are for previous versions of Angular, now Angular17 uses the property "standalone", so then it requires to import and inject right to the component.

Something I tried is adding it as provider in my 'main.ts' file but as well, didn't work.