karma jasmine – Como hacer un test Angular 10 de QueryList

No encuentro en internet como hacer un test de lo siguiente, tengo un componente que tiene estas lineas pero no se como hacer un test de estas partes en Angular 10.

  @ViewChildren('autoCmpl') childComponents: QueryList<InputAutocompleteComponent>;
ngAfterViewInit() {
    this.childComponents.changes.subscribe(_ => {
      this.validateButtonForm();
    });
  }

  
  validateButtonForm() {
    const idxElem = this.childComponents.toArray().findIndex((ele: any) => ele.hasError === true);
    const elemRef = document.getElementById('submit_Button');
    if (idxElem !== -1) {
      elemRef.setAttribute('disabled', 'true');
      elemRef.classList.add('disabled-button');
    } else {
      elemRef.removeAttribute('disabled');
      elemRef.classList.remove('disabled-button');
    }
  }

javascript – No puedo obtener la URL de mi imagen en la versión angular 11

import { Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import { UploadScriptsService } from 'src/app/services/upload-scripts.service';
import { finalize } from 'rxjs/operators';
/*importo el servicio conectionService para mandar datos*/
import { ConectionService } from 'src/app/services/conection.service';
/*importo el Storage de firebase */
import { AngularFireStorage } from '@angular/fire/storage';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-add-card',
  templateUrl: './add-card.component.html',
  styleUrls: ('./add-card.component.css')
})
export class AddCardComponent implements OnInit {


  private script: UploadScriptsService = new UploadScriptsService;
  @ViewChild('imageUser') inputImageUser: ElementRef | undefined;

  /*Variables con las cuales envio los datos para cargar a firebase*/
  item: any = {
    title: '',
    text: '',
    image: ''
  };

  imageSrc: string = "";
  userFile: any;
  imageSelected: any;

/*  DECLARO LAS VARIABLES PARA PODER ENVIAR LA IMAGEN Y OBTENER SU URL */
  imgUrl: Observable<string | any>; 
  uploadPercent: Observable<number | any>; 
  

  constructor(private conection: ConectionService, private storage: AngularFireStorage) {
    this.uploadPercent = new Observable;
    this.imgUrl = new Observable;
  }

  


  ngOnInit(): void {
    this.script.cargaScripts(("uploadCard"))
  }


  addCard() {
    this.conection.addCard(this.item);
    this.item.title = '';
    this.item.text = '';
    this.item.image = '';

  }

  onUpload(e: any)  {
    /* console.log("subir", e.target.files(0)); */

    const id = Math.random().toString(36).substring(2);
    const file = e.target.files(0);
    const filePath = `imagesCards/${id}`;
    const fileRef = this.storage.ref(filePath);
    //Subo la foto
    const task = this.storage.upload(filePath, file);
    //observo el porcentaje de la carga de la imagen
    this.uploadPercent = task.percentageChanges();

    //obtengo el url de la foto
    task.snapshotChanges().pipe(
      finalize(() => { 
        this.imgUrl = fileRef.getDownloadURL()
      })
      )
      .subscribe()
      
      console.log('My ImageUrl' + this.imgUrl);

  }



}

typescript – Rxjs search in Angular

I created an rxjs search for a hiring company, but I got rejected for the following reason:
-performance issue on a bigger data set.
-bugs

My question is how can I make this code better for the next time if I have similar task?

brands = These should be populated from the brand property from the collection of products.

The search should match using the name, description and brand
properties.

  • The search should not fire unless a minimum of three characters have been typed.
  • The search should only fire a maximum of once per 400 milliseconds.

If searching for “xxx” with the brand selected as “xxx” and In Stock, then only products matching all three filters

const stackoverflowFilter = (filter: ISearch) => {
  return (product: IProducts): boolean => {
    return ((
      (
        (product.name.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1) ||
        product.description.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1 ||
        product.brand.toLowerCase().indexOf(filter.input.toLowerCase()) !== -1) &&
      product.brand.toLowerCase().indexOf(filter.select.toLowerCase()) !== -1 &&
      (filter.radio === 'all' ? true : filter.radio === 'in-stock' ? product.quantity > 0 : product.quantity === 0)
    )
    )
  };
};

export interface ISearch { input: string; select: string; radio: string }



> public getStackoverflow(): Observable<Stackoverflow()> {
>         return of((
>           {
>             id: "1",
>             name: "This is just test data",
>             price: "89.9",
>             description: "test data",
>             brand: "stackoverflow",
>             quantity: 4
>           }....))}



 this.stackoverflow$ = this.service.getStackoverflow();

    this.stackoverflow$.pipe(
      tap((prod) => {
        this.stackoverflow = prod;
        this.brands = this.stackoverflow.map(({ brand }) => brand).reduce((prev, cur) => {
          if (prev.indexOf(cur) < 0) prev.push(cur);
          return prev;
        }, ());
      }),
      concatMap(() =>
        this.search$.pipe(
          debounceTime(400),
          distinctUntilChanged(),
          switchMap((search: string) =>
            iif(() => search.length >= 3,
              this.stackoverflow$.pipe(
                map(stackoverflow=> stackoverflow.filter(stackoverflowFilter(this.filter))),
                distinctUntilChanged((curr, prev) => curr === prev),
              ),
              this.stackoverflow$.pipe(
                filter(() => search.length === 0),
              )
            )
          )
        ))
    ).subscribe(
      stackoverflow=> { this.stackoverflow= stackoverflow; },
      (err) => throwError(err)
    );

typescript – Cerrar sesion de forma completa angular?

Quisiera saber como cerrar sesion de forma completa con angular. Me explico:
Mi forma de proteccion de rutas es con un token que guardo en sessionStorage.

Cuando hago el logout (estando en home,por ejemplo), lo que hago es:

sessionStorage.removeItem('token')
navigate('/login')

Esto funciona, el problema es que en ese momento que se redirije al login si vuelvo atras aparece la pantalla de home,cuando no deberia, como si fuese algo del cache etc.

javascript – Angular dynamic Date-picker and dynamic dropdown validation and form submit

I am newbie in Angular and stuck at once place. I want to get JSON on form submit.
The form is custom combination of dynamic dropdown and dynamic mat datepicker.
I am not able to validate or get data on submit.
Here is my code of component .ts and html files

    import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

var R_DATA = {
  "grid": {
    "row": {
      "col": (
        {
          "size": 3,
          "label": "Branch",
          "type": "dropdown",
          "id": "branchCd",
          "default": "${userBranchCd}",
          "ddCd": "4"
        },
        {
          "size": 3,
          "label": "From Date",
          "id": "fromDt",
          "type": "date",
          "default": "${currentDate-7}"
        },
        {
          "size": 4,
          "label": "To Date",
          "id": "toDt",
          "type": "date",
          "default": "${currentDate}"
        }
      )
    }
  }
}

@Component({
  selector: 'app-dynamic-report-viewer',
  templateUrl: './dynamic-report-viewer.component.html',
  styleUrls: ('./dynamic-report-viewer.component.scss')
})
export class DynamicReportViewerComponent implements OnInit {
  testData: string;
  reportData: any;
  showReport: boolean = false;
  @Input() reportForm: FormGroup;
  @Input() reportScreenTitle: string;
  captureParent: any;
  formCol: any;
  formName: string;
  formSubmitted: {};
  constructor() {
    // const currentDate = new Date().getDate;
    // this.minDate = new Date(currentDate - 7);
    // this.maxDate = new Date(currentDate + 1, 11, 31);
   }

  ngOnInit(): void {
    this.testData = '15';
    this.reportData = R_DATA.grid;
    // console.log(this.reportData);
    this.formCol = this.reportData.row.col
    
    
    if(this.reportData){
      this.formCol.forEach(element => {
          this.formName = element.id
      });
    }
    this.reportForm = new FormGroup({
      "this.formName" : new FormControl('', Validators.required)
    })

    
    // this.reportForm.controls('date').hasError('matDatepickerMin')
    // this.reportForm.controls('date').hasError('matDatepickerMax')
  }
  captureData(e: any) {
    this.captureParent = e.text
  }

  
  myFilter = (d: Date | null): boolean =>{
    const day = (d || new Date()).getDay();
    return day !== 0
  }

  loadReport() {
    this.formSubmitted = {
      'this.formName': this.captureParent
    }

    //let getReport = ()
    alert(JSON.stringify(this.formSubmitted))
    // console.log(getReport);
    this.showReport = false;
  }

  onSubmit(){
    // alert(JSON.stringify(this.reportForm.value));
    alert('hi');
  }
}

and here is the respective html

<h2>{{reportScreenTitle}}</h2>
<div class="card" (formGroup)="reportForm" (ngSubmit)="reportForm.valid && onSubmit()">
    <div class="card-header mt-2">
        <div class="grid" *ngIf="reportData">
            <div class="row" *ngIf="reportData.row">
                <div class="col col-{{list.size}}" *ngFor="let list of reportData.row.col">
                    <div (ngSwitch)="list.type">
                        <!-- <input *ngSwitchCase="'textbox'"  (formControlName)="list.id" (id)="list.id" (type)="list.type"> -->
                        <mat-form-field appearance="legacy" *ngSwitchCase="'date'">
                            <mat-label>{{list.label}}</mat-label>
                            <input matInput (matDatepicker)="picker" (id)="list.id" (formControlName)="list.id">
                            <mat-datepicker-toggle matSuffix (for)="picker"></mat-datepicker-toggle>
                            <mat-datepicker #picker></mat-datepicker>
                        </mat-form-field>
                        <div *ngSwitchCase="'dropdown'">
                            <app-dynamic-dropdown (valueChange)="captureData($event)" id="{{list.id}}" name="{{list.id}}" ddCd="{{list.ddCd}}" displayLabel="{{list.label}}" isMandatory="true">
                            </app-dynamic-dropdown>
                        </div>

                    </div>
                </div>
                <div class="col">
                    <button class="btn btn-warning" (click)=loadReport()>Submit</button>
                </div>
            </div>
        </div>
    </div>
    <div class="card-body">
        <iframe id="dynamic_report_iframe" *ngIf="showReport" width="100%" height="500px" ></iframe>
    </div>
</div>

Any help or suggestion will be appreciated!

angular – Error AngularJS y HTML

Buenas tengo un eror a la hora de cargar el html me da bastantes errores en la consola del navegador, creo que es por tener importadas tantas librerias, lo que quiero es mostrar un modal al pulsar el boton pero no funciona de la manera correcta.

Aqui dejo el codigo del HTML con todas las librerias importadas, he probado a quitar algunas o cambiar la version pero nada y pasandolo por el comprobador de html me dice que esta correcto todo.

   <!DOCTYPE html>
  <html data-ng-app="plunker" lang="es">

 

  <head>
    <meta charset="utf-8" />
    <title>PracticaRDE</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap-tpls.min.js"></script>
    <script src="app.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-animate.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.css">

    
     <style>
        table, th , td  {
          border: 1px solid grey;
          border-collapse: collapse;
          padding: 5px;
        }
        table tr:nth-child(odd) {
          background-color: #f1f1f1;
        }
        table tr:nth-child(even) {
          background-color: #ffffff;
        }
        
        /* Slideshow style */
.splash {
    position: fixed;
    background: rgba(0,0,0,0.85);
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 500;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    -webkit-perspective: 1000px;
    perspective: 1000px;
    transition: opacity 0.5s, visibility 0s 0.5s;
    -webkit-transition: opacity 0.5s, visibility 0s 0.5s;
}

.splash-open.splash {
    opacity: 1;
    visibility: visible;
    -webkit-transition: opacity 0.5s;
    transition: opacity 0.5s;
}

.splash .splash-inner {
    width: 100%;
    height: 100%;
    -webkit-transform-style: preserve-3d;
    transform-style: preserve-3d;
    -webkit-transform: translate3d(0,0,150px);
    transform: translate3d(0,0,150px);
    -webkit-transition: -webkit-transform 0.5s;
    transition: transform 0.5s;
}


.splash-open.splash .splash-inner {
    -webkit-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}

.splash .splash-content {
    width: 660px;
    height: 350px;
    position: absolute;
    top: 40%;
    left: 50%;
    margin: -175px 0 0 -330px;
    color: #fff;
    font-size: 18px;
}

.splash-content h1 {
    color: #fff;
    margin-bottom: 40px;
}


.btn-outline {
    margin-top: 40px;
    color: #fff;
    border: 2px solid #fff;
    border-radius: 2px;
    background-color: transparent;
    width: 250px;
    font-weight: 300;
}
.btn-outline:hover {
    color: #fff;
    background-color: rgba(255, 255, 255, 0.05);
}
        
        </style>
  </head>


 

  <body data-ng-app="plunker" data-ng-controller="MainCtrl as ctrl">





    <div data-ng-show = "true">

 


      <uib-tabset active="ctrl.active">

 

        <uib-tab index="1" heading="Comercial">

 

         <form name="myForm">
          <label>
           Nombre:
           <input type="text" name="nombrecom"  pattern="(a-zA-Z ){2,254}" placeholder="Introduzca su Nombre" title="Debe introducir un nombre"  data-ng-model="user.name" required>
         </label>
         <div role="alert">
          <span class="error" data-ng-show="myForm.userName.$error.required">
          </span>
        </div>
        <button> insertar </button> <button>borrar</button>
            <br><br>

  <div class="row">
      <div class="col-md-12 text-center">
        <button class="btn btn-lg btn-success" data-ng-click="ctrl.openSplash()">Buscar Comercial</button>
      </div>
    </div>
        
        
      </form>


        <table>
          <thead>
                <tr><td><b>Id</b></td><td><b>Nombre</b></td></tr>
          </thead>
          <tr data-ng-repeat="x in names">
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
 
 




    </uib-tab>

 


    <uib-tab index="2" heading="Cliente">
      <form name="myForm">
         <label>
         DNI:
         <input type="text" name="dni" placeholder="Introduzca su DNI" pattern="(0-9){8}(A-Za-z){1}" required title="Debe poner 8 números y una letra" />
       </label>
       <br>
        <label>
         Nombre:
         <input type="text" name="nombrecli" pattern="(a-zA-Z ){2,254}" placeholder="Introduzca su Nombre" data-ng-model="user.name" required>
       </label>
       <br>
        
      <button> insertar </button> <button>borrar</button>
        <br><br>

        <table>
          <thead>
              <tr><td><b>DNI</b></td><td><b>Nombre</b></td></tr>
          </thead>
          <tr data-ng-repeat="x in names">
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
    </form>

 

  </uib-tab>

 


  <uib-tab index="3" heading="Coche">

 

    <form name="myForm">
      <label>
       Matricula:
        <input type="text" name="dni" placeholder="Introduzca su Matricula" pattern="(0-9){4}(A-Za-z){3}" required title="Debe poner 4 números y 3 letras" />
       </label>
   <br>
     <label>
         Marca:
         <input type="text" name="marca" placeholder="Introduzca su Marca" pattern="(a-zA-Z ){2,254}" title="Debe introducir una marca de coche" data-ng-model="user.name" required>
       </label>
       <br>
       <label>
         Modelo:
         <input type="text" name="modelo" placeholder="Introduzca su Modelo" pattern="(a-zA-Z ){2,254}" title="Debe Introducir un modelo de coche"  required>
       </label>
     <div role="alert">
      <span class="error" data-ng-show="myForm.userName.$error.required">
      </span>
    </div>
    <button> insertar </button> <button>borrar</button>
    <br><br>
        <table>
          <thead>
                <tr><td><b>Matricula</b></td><td><b>Marca</b></td><td><b>Marca</b></td></tr>
          </thead>
          <tr data-ng-repeat="x in names">
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
    
  </form>

 


</uib-tab>

 

</uib-tabset>

</div>

 

</body>

 

</html>

Aqui os dejo el codigo del JavaScript con el controller creado y las funciones para mostrar el modal que creo que esta de forma correcta:

 var app = angular.module('plunker', ('ui.splash'));



app.controller('MainCtrl', ('$splash', function($scope, $splash) {
  var self = this;
  
    $scope.name = 'World';

   self.buttonClicked = function(index) {
    self.show_tabs = true;
    self.active = index;
  };
  
  self.closeTab = function(){
    self.show_tabs = false;
  };
  
 this.openSplash = function () {
    $splash.open({
      title: 'Hi there!',
      message: "This sure is a fine modal, isn't it?"
    });
  };
    
}));

// Re-usable $splash module
angular.module('ui.splash', ('ui.bootstrap', 'ngAnimate'))
.service('$splash', (
  '$uibModal',
  '$rootScope',
  function($uibModal, $rootScope) {
    return {
      open: function (attrs, opts) {
        var scope = $rootScope.$new();
        angular.extend(scope, attrs);
        opts = angular.extend(opts || {}, {
          backdrop: false,
          scope: scope,
          templateUrl: 'splash/content.html',
          windowTemplateUrl: 'splash/index.html'
        });
        return $uibModal.open(opts);
      }
    };
  }
))
.run((
  '$templateCache',
  function ($templateCache) {
    $templateCache.put('splash/index.html',
      '<section modal-render="{{$isRendered}}" class="splash" modal-in-class="splash-open" ng-style="{'z-index': 1000, display: 'block'}" ng-click="close($event)">' +
      '  <div class="splash-inner" ng-transclude></div>' +
      '</section>'
    );
    $templateCache.put('splash/content.html',
      '<div class="splash-content text-center">' +
      '  <h1 ng-bind="title"></h1>' +
      '  <p class="lead" ng-bind="message"></p>' +
      '  <button class="btn btn-lg btn-outline" ng-bind="btnText || 'Ok, cool'" ng-click="$close()"></button>' +
      '</div>'
    );
  }
));

El error debe de ser de las librerias pero no tengo ni idea de que puede estar pasando, gracias de antemano.

Angular – Failed to Compile – Property ‘url’ does not exist on type ‘Object’

Failed to compile.

src/app/app.component.html:3:14 – error TS2339: Property ‘url’ does not exist on type ‘Object’.

3 [url]=”photo.url”
~~~

src/app/app.component.ts:6:16
6 templateUrl: ‘./app.component.html’,
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.

angular – TypeError: Cannot read property ‘projectPath’ of undefined when create amplify

I try to build a web app , using front-end as angular and back-end as amplify.

I created angular app after that i add the following to your src/polyfills.ts file to recreate them:

(window as any).process = {
  env: { DEBUG: undefined },
};

Next step i create new amplify back-end

amplify init

after showing this error:

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project amplifyapp
The following configuration will be applied:

Project information
| Name: amplifyapp
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
TypeError: Cannot read property 'projectPath' of undefined
    at getAngularConfig (/snapshot/node_modules/amplify-frontend-javascript/lib/framework-config-mapping.js:57:52)
    at getProjectConfiguration (/snapshot/node_modules/amplify-frontend-javascript/lib/framework-config-mapping.js:85:14)
    at Object.displayFrontendDefaults (/snapshot/node_modules/amplify-frontend-javascript/lib/configuration-manager.js:173:32)
    at Object.displayFrontendDefaults (/snapshot/node_modules/amplify-frontend-javascript/index.js:40:24)
    at displayAndSetDefaults (/snapshot/node_modules/@aws-amplify/cli/lib/init-steps/s0-analyzeProject.js:83:26)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async analyzeProject (/snapshot/node_modules/@aws-amplify/cli/lib/init-steps/s0-analyzeProject.js:99:9)
    at async Object.run (/snapshot/node_modules/@aws-amplify/cli/lib/commands/init.js:29:13)
    at async Object.executeAmplifyCommand (/snapshot/node_modules/@aws-amplify/cli/lib/index.js:236:9)
    at async executePluginModuleCommand (/snapshot/node_modules/@aws-amplify/cli/lib/execution-manager.js:164:5)
    at async Object.executeCommand (/snapshot/node_modules/@aws-amplify/cli/lib/execution-manager.js:35:9)
    at async Object.run (/snapshot/node_modules/@aws-amplify/cli/lib/index.js:112:9)