Code Refractoring for Dynamic List in Angular 8

With a specific requirement of showing/hiding the pages, the following implementation has been carried out.

The pages which needs to be hidden will be provided through an array

this.unshowPages = ('menuPage', 'aboutusPage','linkedInPage');

The corresponding HTML file,

 <ng-container *ngIf="showaboutPages">
        <li>
          <a  routerLink="#" routerLinkActive="active">           
            About us Page
          </a>
        </li>
      </ng-container>
       <ng-container *ngIf="showlkdPages">
        <li>
          <a  routerLink="#" routerLinkActive="active">           
            LinkedIN Page
          </a>
        </li>
      </ng-container>

The ts file will be

unshowPages= ();

showMenuPages: boolean = true;
showaboutPages: boolean = true;
showlkdPages: boolean = true;

ngOnInit() {
//this.unshowPages = ('menuPage', 'aboutusPage','linkedInPage');
this.unshowPages = ('menuPage');

this.unshowPages.forEach((x:string)=> {

  console.log(x)

  switch(x){
    case 'menuPage': this.showMenuPages = false; break;
    case 'aboutusPage': this.showaboutPages = false; break;
    case 'linkedInPage': this.showlkdPages = false; break;

  }

  });

The problem comes here is when pages gets updated, the switch case should be modified to adapt new pages. Is there any optimized way to achieve this.

The minimal reproducible working code : https://stackblitz.com/edit/angular-ivy-1antde

angular – Detectar cambios en user authentification Firebase

Estoy creando un proyecto en angular y Firestore y tengo el siguiente problema:
Cuando registro un usuario pido verificar por correo, para lo cual necesito observar si el correo ya esta verificado y cambiar la ruta.
Tengo el siguiente código que es un observable del usuario, pero cuando se verifica no me detecta el cambio a menos que actualice la pagina manualmente:

 public userData$: Observable<firebase.User>;

 constructor( private afAuth: AngularFireAuth){}
this.userData$ = afAuth.authState;

Trate con el siguiente código, pero tampoco consigo poder observar los cambios.

this.userData$ = Observable.create(obs => afAuth.auth.onAuthStateChanged(obs));

Espero me puedan ayudar. Gracias

angular – HttpInterceptor not calling Global Error Handler

I am performing a spike to investigate the global error handler within Angular, I am trying to simulate client side and server side errors but when I force a http error(fake end point) the errors seem to get outputted to the console instead of getting dealt with the error handler, meaning they don’t even call through to the error handler.

ErrorHandler

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private injector: Injector) { }

    handleError(error: Error | HttpErrorResponse): void {
      const errorService = this.injector.get(ErrorService);
      const notifier = this.injector.get(NotificationService);

      let message;
      let stackTrace;
      if(error instanceof HttpErrorResponse){
          //Server error
          message = errorService.getServerMessage(error);
          stackTrace = errorService.getServerStack(error);
      }else{
          //Client Error
          message = errorService.getClientMessage(error);
          stackTrace = errorService.getClientStack(error);
      }
      notifier.showError(message);
    }
}

Interceptor

export class ServerErrorInterceptorService implements HttpInterceptor {

  constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError((error: HttpErrorResponse) => {
                if (error.error instanceof ErrorEvent) {
                    // client-side error or network error

                } else {
                    // TODO: Clean up following by introducing method
                    if (error.status === 498) {
                        // TODO: Destroy local session; redirect to /login
                    }
                    if (error.status === 401) {
                        // TODO: Permission denied; show toast
                    }
                }
                return throwError(error);
            })
        )
    }
}

Module provider:

providers: (
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
    { provide: HTTP_INTERCEPTORS, useClass: ServerErrorInterceptorService, multi: true}
)

and component:

    export class ErrorHandlingComponent implements OnInit {

  constructor(private httpClient: HttpClient) { }

  numberArray: number();

  ngOnInit() {
  }

  causeError(){
       this.numberArray(-1) = 1;
  }

    causeServerSideError() {
        this.httpClient.get("STUB URL").subscribe((x: number()) => this.numberArray = x)
    }
}

angular – ERROR Error: Uncaught (in promise): Error: NodeInjector: NOT_FOUND [ControlContainer]

Quiero crear un formulario reactivo con ionic (6.9.0) Angular(9.1.7) llevo con este error un par de días y no doy con la solución ni se porque es:

introducir la descripción de la imagen aquí

app.module.ts he añadido los import ReactiveFormsModule, FormsModule

import { ReactiveFormsModule, FormsModule } from '@angular/forms';
imports: ( ReactiveFormsModule, FormsModule),

registro.page.ts con formbuilder agrupo los campos del form, con validator hago las validaciones

     import { Component, OnInit } from '@angular/core';
     import { FormBuilder, Validators } from '@angular/forms';
       @Component({
       selector: 'app-registro',
        templateUrl: './registro.page.html',
       styleUrls: ('./registro.page.scss'),
     })
export class RegistroPage implements OnInit {

  get name(){
    return this.registrationForm.get('name');
  }
  get email(){
    return this.registrationForm.get('email');
  }
  get password(){
    return this.registrationForm.get('password');
  }

  public errorMessages = {
    name:(
      { type: 'required', message:'Nick requerido'},
      { type: 'minlength', message:'mínimo 4 caracteres'},
      { type: 'maxlength', message:'maxímo 12 caracteres'},
    ),

    email:(
      { type: 'required', message:'Email requerido'},
      { type: 'pattern', message:'Ingrese un correo electronico valido'},
    ),

    password:(
      { type: 'required', message:'Password requerido'},
      { type: 'minlength', message:'mínimo 6 caracteres'},
      { type: 'maxlength', message:'maxímo 12 caracteres'},
    )
 };

 private emailPattern:string='^(a-zA-Z0-9_.+-)+@(a-zA-Z0-9-)+.(a-zA-Z0-9-.)+$';

 registrationForm = this.formBuilder.group({
   name:('', (Validators.required, Validators.minLength(4), Validators.maxLength(12))),
   email:('', (Validators.required, Validators.pattern(this.emailPattern))),
   password:('', (Validators.required, Validators.minLength(6), Validators.maxLength(12)))
 });


  constructor(private formBuilder: FormBuilder ) {

  }

  ngOnInit() {

  }

  public submit(){
    console.log(this.registrationForm.value);
  }
}

registro.page.html formulario con los campos name, email y password. (formGroup)=”registrationForm”

<form (formGroup)="registrationForm" (ngSubmit)="submit()">
      <ion-list style="background: transparent;" class="background-input">
        <ion-item>
          <ion-label position="floating">Nombre</ion-label>
          <ion-input formControlName="name" autocapitalize inputmode="text"></ion-input>
        </ion-item>
        <div *ngFor="let error of errorMessages.name">
          <ng-container *ngIf="name.hasError(error.type) && (name.dirty || name.touched)">
            <small class="error-message">{{error.message}}</small>
          </ng-container>
        </div>

        <ion-item>
          <ion-label position="floating">Email</ion-label>
          <ion-input formControlName="email" inputmode="email"></ion-input>
        </ion-item>
        <div *ngFor="let error of errorMessages.email">
          <ng-container *ngIf="email.hasError(error.type) && (email.dirty || email.touched)">
            <small class="error-message">{{error.message}}</small>
          </ng-container>
        </div>

        <ion-item>
          <ion-label position="floating">password</ion-label>
          <ion-input formControlName="password" inputmode="password"></ion-input>
        </ion-item>
        <div *ngFor="let error of errorMessages.password">
          <ng-container *ngIf="password.hasError(error.type) && (password.dirty || password.touched)">
            <small class="error-message">{{error.message}}</small>
          </ng-container>
        </div>
      </ion-list>

      <ion-button (disabled)="!registrationForm.valid" type="submit" color="tertiary" expand="block" class="ion-margin-top" >
        Registrarme
        <ion-icon slot="end" name="create"></ion-icon>
      </ion-button>

He estado mirando en problemas parecidos que hay en stackoverflow pero no me resuelven el error.
Cualquier ayuda sera bien recibida.

Gracias de antemano!

javascript – Angular ngFor adicionar condicional usnado ng-content

Estou usando primeng para renderizar dados numa tabela, segue conforme documentação meus dados e minha config de colunas

   API {
      id: 1,
      nome: "Test 1",
      moeda: "Euro",
      status: "Recebido",
      data: "01/01/1999",
    }

 ngOnInit {
   this.col = [
     {field: 'nome', header: 'Nome'},
     {field: 'moeda',  header: 'Moeda'},
     {field: 'status', header: 'Status'},
     {field: 'data', header: 'Data'}
   ]
}

Bom, faço um ngFor e renderinzo cada coluna e seus respectivos dados com sucesso

<td *ngFor="let col of column">
    {{rowData[col.field]}}
</td>

Agora o problema, para cada coluna de dados na inha tabela preciso formatar de acordo, por exemplo, a coluna Data precisa usar um pipe para formar da data, para outros campos preciso fazer outras alterações, podendo usar pipe.

<td *ngFor="let col of columns | keyvalue">
  <ng-container *ngIf="rowData[col.field] !== 'data'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'data'"> {{rowData[col.field] | date: 'dd/MMM/yyyy'}}</ng-container>
</td>

Como que eu faço por exemplo nesse contexto acima se eu tiver que também usar pipe de uppercase na coluna nome, ou tiver que usar pipe de currency na coluna moeda como que faço par renderizar tudo isso dentro de um ng-container.

Se for data teria que vir com data formatada, se for nome em uppercase, se for moeda com currency, enfim como faço refactoy desse codigo abaixo?

<td *ngFor="let col of columns | keyvalue">
  <ng-container *ngIf="rowData[col.field] !== 'data'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'data'"> {{rowData[col.field] | date: 'dd/MMM/yyyy'}}
  <ng-container *ngIf="rowData[col.field] !== 'moeda'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'moeda'"> {{rowData[col.field] | currency:'CAD':'code'}'}}
  <ng-container *ngIf="rowData[col.field] !== 'nome'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'nome'"> {{rowData[col.field] | uppercase}}</ng-container>
</td>

angular – how to throw an error after retrying rxjs 6

I’m having trouble with the return error in my retry sentence:

What I want to do is retry and httpRequest 10 times before consider it wrong, if it fails the 10 times, then throw the error to be catched by ErrorHandler:

private handleError(error, req: HttpRequest<any>, next: HttpHandler): Observable<any> {

  if (error.status === 0) {
    return next.handle(req).pipe(
      retryWhen(errors => errors.pipe(delay(1000), take(2), concatMap(throwError(errors)))));

  }
}

If I remove the concatMap it works, but with this I’m not able to make it works. How can I solve it?

json – ¿Como crear un filtro de busqueda en rangos de fecha con Angular?

Hola un coordia Saludos comunidad SO.

Estoy tratando de crear un filtro pipe de filtro de rango de fechas en Angular, trayendo data desde una API pero honestamente no se como manejar la data de Fecha de la API, no viene en un formado correcto de fecha.

Primero tengo este service de data traida desde FireBase( sientanse libres de probar la url)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class VentasService {
  private url = 'https://loggin-app-fa0a7.firebaseio.com/data.json';
  constructor(private http: HttpClient) {
  }


  getVentas() {
    return this.http.get(this.url);
  }

  getClientes() {
    return this.http.get('https://loggin-app-fa0a7.firebaseio.com/data/clientes.json');
  }

  getFacturas() {
    return this.http.get('https://loggin-app-fa0a7.firebaseio.com/data/facturas.json');
  }

}

Luego tengo este pipe que es donde estoy tratando de crear el filtro

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtroFecha'
})
export class FiltroFechaPipe implements PipeTransform {

  transform(row: any, f1: any, f2?: any): any {

    const resultadoFiltro = ();
// si es menor a la fecha final
    if (f1 >= f2 || f1 === '') {
      return row;
    }
// si el argumento de fecha final es invalido, se setea a la fecha actual
    if (f2 === '') {
      f2 = new Date().getTime();
    }
// si ambos arreglos son correctos entonces se crea el nuevo arrego
    for (const filteredRow of row) {
      if (row.fecha > f1 && row.fecha < f2 ) {
        resultadoFiltro.push(filteredRow);
      }
    }
    return resultadoFiltro;


}

}

Y este el componente donde trato de aplicar el pipe

import { Component, OnInit } from '@angular/core';
import { VentasService } from 'src/app/services/ventas.service';
// date time picker
import { IMyDpOptions } from 'mydatepicker';

@Component({
  selector: 'app-facturas',
  templateUrl: './facturas.component.html',
  styles: ()
})
export class FacturasComponent implements OnInit {

  desde = '';
  hasta = '';
 // incializando date time picker
  public myDatePickerOptions: IMyDpOptions = {
    // Opciones
    dateFormat: 'dd.mm.yyyy',
  };

  // almacena facturas
  facturas: any = ();

  constructor(private ventas: VentasService) { }

  ngOnInit() {
    this.ventas.getFacturas().subscribe((data: any) => {
      this.facturas = data;
      console.log('Facturas works');
      console.log('================');
      console.log(this.facturas);
    });
  }
}

Y acá el template

div class="my-auto">
  <div class="row d-flex justify-content-center mt-2 animated fadeIn">
    <p class="h1">Facturas Resientes</p>
  </div>
  <!-- Header  -->

  <!-- filtros -->
  <div class="row d-flex justify-content-around">
    <div class="col-md-4">
      <!-- date time picker component -->
      <form #myForm="ngForm" novalidate>
        <my-date-picker name="mydate" (options)="myDatePickerOptions"
                        ((ngModel))="desde" required placeholder="Desde">
        </my-date-picker >
    </form>
     <!-- date time picker component-->
    </div>
    <div class="col-md-4">
      <form #myForm="ngForm" novalidate>
        <my-date-picker name="mydate" (options)="myDatePickerOptions"
                        ((ngModel))="hasta" required placeholder="Hasta" >
         </my-date-picker>
    </form>
    </div>
  </div>


<!-- filtros -->

  <!-- tabla de clientes -->
  <div class="row card animated fadeIn" id="agenda">
    <table class="table table-borderless table-responsive-md">
      <thead>
        <tr>
          <th scope="col">Empresa</th>
          <th scope="col">Monto</th>
          <th scope="col">Estado</th>
          <th scope="col">Fecha</th>
        </tr>
      </thead>
      <tbody>
        <!-- aplicando el pipe al ng-for -->
        <tr *ngFor="let factura of facturas|filtroFecha:desde :hasta">
          <td>{{factura.empresa}}</td>
          <td>{{factura.monto | currency}}</td>
          <td>{{factura.estado}}</td>
          <td>{{factura.fecha}}</td>
        </tr>
      </tbody>
    </table>
 <!-- tabla de clientes -->

Pero no filtra nada

esta es la url de donde obtengo la info
https://loggin-app-fa0a7.firebaseio.com/data/facturas.json

y este el resultado

(
    {
        "empresa": "Wallmark",
        "estado": "pendiente",
        "fecha": "16/12/2019",
        "monto": 2000
    },
    {
        "empresa": "Corte Ingles",
        "estado": "pendiente",
        "fecha": "02/04/2020",
        "monto": 2345555
    },
    {
        "empresa": "innovatek",
        "estado": "pagada",
        "fecha": "23/2/2020",
        "monto": 300000
    },
    {
        "empresa": "holeee",
        "estado": "pagada",
        "fecha": "20/11/2019",
        "monto": 790000
    },
    {
        "empresa": "everlast",
        "estado": "pagada",
        "fecha": "09/06/2019",
        "monto": 568999
    }
)

La fecha esta en tipo string y bueno he ahi el problema que no se como manejar la data de esa forma realmente.

Espero me puedan ayudar se los agradeceria mucho amigos de SO

testing – What do you unit test in your angular applications?

I am currently working in a team, which, when I joined them did not do any sort of unit or integration testing.

Over the last 2 years I have bit by bit pushed dotnet unit testing to a point where it is now considered part of day to day workflow. Integration testing have also had a place and are coming up once again as a point of focus which is great. The team generally agrees that dotnet unit tests are definitely worth it and that dotnet integration tests are also a great addition, although they take longer to write and set up.

The area where unit tests are almost non-existent is our angular/UI code. I’ve pushed for us to add unit tests for re-usable functions, etc, however component unit testing has largely been left alone as both myself and the rest of the team struggle to quantify whether it is worth it or not. A few attempts to add unit testing to the UI have ended up with us writing a bunch of unit tests, however none of us really understood the value.

Just recently, an experienced (and quite openly opinionated) front-end developer joined the team and his opinion is that angular UI unit testing is completely and utterly worthless. I am afraid of simply agreeing with this point of view as this was similar to the team’s opinion about dotnet unit testing initially and now they think the opposite.

Question:
What do you test in your angular application and how do you think it improves your software quality/stability?

Possible discussion points:
Do you have unit tests? If so – what do you test? Components? Services? State? Actual DOM changes? Do you instead have end to end tests? How would you quantify the time(cost) vs benefit?

Any insight/etc would be highly valued!

Thanks!

¿Como simular un join en Firebase entre dos documentos en Angular?

Tengo dos documentos en firebase, uno es usuarios y el otro son publicaciones, entonces en el documento de usuarios están todos los datos de un usuario y en publicaciones sus datos pero con el uid de quien lo publicó, pero no se como simular un join entre dos documentos, ya que quiero hacer un apartado donde se muestren todas las publicaciones y quien las publicó pero no se como hacer para que a partir del uid de publicaciones poder traerme la información de usuarios tal como nombre, correo etc.

Adjunto imagenes
Documento publicaciones

Documento usuarios

Aqui es donde no me imagino como realizarlo
Ejemplo de como quisiera hacer el servicio

Y esto es como quisiera que se mostrara, la información de la publicación y el nombre de usuario
Como quisiera que fuera al final