Angular 6 – httpClient Error message not from response error data Ask Question

I am using Angular 6 httpClient and I am having issues with the error responses.

Here is the code:

postIt() {
    return this.http.post(URL, { ...httpOptions, responseType: 'text', observe: 'response' }).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.log('There was an error: ', error);
      }
    );
  }

The problem here is that it’s returning error’s like 400 (Bad Response) and not the error message that is available in httpErrorResponse.
There is a field called Error: “This record cannot be edited” … this actually is telling me what’s wrong.

How can I get that message instead of the other?

Angular 5 Reactive Forms : There is no directive with “exportAs” set to “ngModel” Ask Question

I’m working on angular 5 Reactive Forms :
I had this error :
There is no directive with “exportAs” set to “ngModel”
I saw in others forums that problem can be for many reasons :
misspelling in the HTML template , forgetting to import “FormsModule” or “ReactiveFormsModule”, ….

I checked my code but i didn’t find the issue
Can you Help me please !!!

Console error :

There is no directive with "exportAs" set to "ngModel" (" 
    [(ngModel)]="user.FirstName" 
    formControlName="FirstName"
    [ERROR ->]#FirstName="ngModel" />
    <label for="firstName">{{ 'FIRST_NAME' | translate:param}}</label>")
   : ng:///AppModule/LoginComponent.html@12:15

app.module.ts:

//angular moudel
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
....

@NgModule({
  declarations: [
    .....
  ],
  imports: [
    BrowserModule,
    FormsModule, 
    ReactiveFormsModule, 
     ...
    AppRoutingMoudel,
  ],
    ...
})

LoginComponent.ts

import { Component, OnInit } from '@angular/core';
import { User } from './../../../model/user';
import {FormBuilder,FormGroup,FormControl,Validators,NgForm} from  '@angular/forms'
        ....
 export class LoginComponent implements OnInit {

     user : User;
     userLoginForm: FormGroup;

      constructor(private userLoginFormBuilder:FormBuilder) { 

        this.user = new User ("TestName", "Yagmi",
                                    "TestName@Yagmi.com", "esay", "esay");

        this.userLoginForm = this.userLoginFormBuilder.group({
                        FirstName: new FormControl (this.user.FirstName,
                                         [Validators.minLength(4),])
            });
         }
    }

LoginComponent.Html

<form class="col s12" [formGroup]="userLoginForm" (ngSubmit)="saveUserLogin()">

    <div class="row">
      <div class="input-field col s12 m6">

        <input id="firstName" 
               type="text" 
               class="validate"
               [(ngModel)]="user.FirstName" 
               formControlName="FirstName"
               #FirstName="ngModel" />

        <label for="firstName">{{ 'FIRST_NAME' | translate:param }}</label>
        <p class="data-error data-validation" *ngIf="FirstName.errors?.minlength">
          min length is 4 caracters.
        </p>
        <p class="data-error data-validation" *ngIf="FirstName?.touched">
          touched.
        </p>

      </div>
    </div>
  </form>

user.ts

export class User {
    constructor(
        public FirstName: string,
        public LastName: string,
        public Email: string,
        public Passeword: string,
        public ConfirmPasseword: string
   )
}

Javascript/Angular 5 – clicking multiple buttons only affects one Ask Question

I have a grid of 4 buttons and once one of them is clicked it will call a function called doSearch which checks which button was clicked and based on that assigns a string to the last_search value.

However, when I click any of the four buttons, I always seem to only press the edm button and reads ‘i am edm’ to console.

Could anyone explain why that is?

html

<!-- grid for music -->
<ng-container *ngIf="show" >
  <div class="mdl-grid">
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="edm-btn" type="submit" (click)="doSearch($event)">EDM</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="house-btn" type="submit" (click)="doSearch($event)">House</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="pop-btn" type="submit" (click)="doSearch($event)">Pop</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="dubstep-btn" type="submit" (click)="doSearch($event)">Dubstep</button>
    </div>
  </div>
</ng-container>

function code

doSearch(event): void {

    if (document.getElementById('edm-btn')) {
      this.last_search = 'edm';
      console.log('i am edm');
    } else if (document.getElementById('house-btn')) {
      this.last_search = 'house';
      console.log('i am house');
    } else if (document.getElementById('pop-btn')) {
      this.last_search = 'pop';
      console.log('i am pop');
    } else if (document.getElementById('dubstep-btn')) {
      this.last_search = 'dubstep';
      console.log('i am dubstep');
    }
}

FIX:

instead of passing the id of the button, I decided to pass a string directly into the function call of doSearch

html

<!-- grid for music -->
<ng-container *ngIf="show" >
  <div class="mdl-grid">
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="edm-btn" type="submit" (click)="doSearch('edm')">EDM</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="house-btn" type="submit" (click)="doSearch('house')">House</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="pop-btn" type="submit" (click)="doSearch('pop')">Pop</button>
    </div>
    <div class="mdl-cell mdl-cell--1-col">
      <button mat-button id="dubstep-btn" type="submit" (click)="doSearch('dubstep')">Dubstep</button>
    </div>
  </div>
</ng-container>

function

doSearch(category): void {

    console.log(JSON.stringify(category, null, 2));
    if (category === 'edm') {
      this.last_search = 'edm';
      console.log('i am edm');
    } else if (category === 'house') {
      this.last_search = 'house';
      console.log('i am house');
    } else if (category === 'pop') {
      this.last_search = 'pop';
      console.log('i am pop');
    } else if (category === 'dubstep') {
      this.last_search = 'dubstep';
      console.log('i am dubstep');
    }
}

Error: http://localhost/node_modules/@types/node/index.d.ts: interface is a reserved word in strict mode Ask Question

I am integrating an AngularJS application within an Umbraco project. I have a cs-html file which calls the main.js file of my app and the aplication displays in a designated URL( All this after the project has run tsc and build).

The folder structure is as follows:

UmbracoProject/
              |
              | angularCode/
              |              src/
              |              systemjs-angular-loader.js
              |              systemjs.config.js
              |              tsconfig.js
              |
              |node_modules/
                           @types/node/index.d.ts

I have to configure the systemjs.config.js file so that the imports from the angular app isable to find the node_modules. (It is set this way because there will be other angular apps in the same project so that all share the same node_modules).

I am using some of the dependencies for fabric.js require the @types/node/index.d.ts file in order to run.

My systemjs.config.js must find the following

When i go to the designed url, I recieve the following error:

Error: http://localhost/node_modules/@types/node/index.d.ts: interface is a reserved word in strict mode (18:0)
  16 | 
  17 | // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
  18 | interface Console {
     | ^
  19 |     Console: typeof NodeJS.Console;
  20 |     assert(value: any, message?: string, ...optionalParams: any[]): void;
  21 |     dir(obj: any, options?: NodeJS.InspectOptions): void;
  Instantiating http://localhost/node_modules/@types/node/index.d.ts

Any leads on this kind of issue?

Thanks

Angular 2 & Autonumeric.js – problems on .multiple Ask Question

I receive this error in a component when I’m using this plugin:

ERROR TypeError: Cannot read property ‘multiple’ of undefined
at PreventiviTableComponent.ngAfterViewInit (advanced-search.component.ts:629)
at callProviderLifecycles (core.es5.js:11189)
at callElementProvidersLifecycles (core.es5.js:11164)
at callLifecycleHooksChildrenFirst (core.es5.js:11148)
at checkAndUpdateView (core.es5.js:12253)
at callViewAction (core.es5.js:12610)
at execEmbeddedViewsAction (core.es5.js:12568)
at checkAndUpdateView (core.es5.js:12246)
at callViewAction (core.es5.js:12610)
at execComponentViewsAction (core.es5.js:12542)


I use the plugin this way:
ngAfterViewInit() {

            AutoNumeric.multiple(['#filtroImportoMin', '#filtroImportoMax'], {
                digitGroupSeparator: '.',
                decimalCharacter: ',',
                modifyValueOnWheel: 'false',
                decimalPlaces: 0
            })

}

And in the same component I have imported autonumeric like this:

import { AutoNumeric } from ‘autonumeric’;.

If I put an “windows.setTimeout” near my function it seems to work (but now well in really…).

I didn’t imported autonumeric in my app.modules because I meet some issues.

I just imported it in my Angular-cli.json this way

"scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/bootstrap-slider/dist/bootstrap-slider.min.js",
        "../node_modules/underscore/underscore-min.js",
        "../node_modules/list.js/dist/list.min.js",
        **"../node_modules/autonumeric/dist/autoNumeric.min.js",**
        "../node_modules/chart.js/dist/Chart.min.js",
        "main.js"

        ]

I’m trying to resolve this issue by 2 days but nothing…This plugin seems to work on some components, not in others…

How to filter the contents by manually typing number and filtering using angular2 Ask Question

I have totally 4 fields to filter the table contents. If i put 2 values in filter section it works, if i add one more field in that not even one works. Can anyone help me to filter the contents, based on email and phone number as well.

enter image description here
HTML:
The upper part of code for using filter data:

<ng-select [options]="name" [(ngModel)]="filter.name"></ng-select>
      <ng-select [options]="email" [(ngModel)]="filter.email"></ng-select>
      <input type="number" onKeyPress="if(this.value.length==10) return false;" class="form-textbox input-text" [(ngModel)]="filter.phone_number">
      <ng-select [options]="pinAddress" [(ngModel)]="filter.address"></ng-select>

pipe used to filter the table:

<tbody>
          <tr *ngFor="let pin of pins | pinfilter:filter">
            <td>{{pin.name}}</td>
            <td>{{pin.description}}</td>
            <td>{{pin.address}}</td>
            <td>{{pin.website}}</td>
            <td>{{pin.phone_number}}</td>
            <td>{{pin.email}}</td>
            <td>{{pin.comments}}</td>
          </tr>
        </tbody>

TS:

filter.pipe.ts:
/* Tutorial filter to write filter functions for Tutorial*/
import { Pipe, PipeTransform } from '@angular/core';

export class NewPin { 
  public _id:number;
  public user_id:number;
  public name:string;  
  public address:string;
  public phone_number:string;
  public email:string;
  public comments:boolean;
}

@Pipe({
  name: 'pinfilter',
  pure: false
})

export class PinPipe implements PipeTransform { 
  transform(items: NewPin[], filter: NewPin): NewPin[] { 
    if (!items || (!filter.name && !filter.address)) { 
      return items; 
    } 
      return items.filter((item: NewPin) => this.applyFilter(item, filter)); 
  } 

  applyFilter(user: NewPin, filter: NewPin): boolean {
    console.log(filter);
    if (filter.name && filter.address) { 
      if (filter.name == user.name && filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else if (filter.name) { 
        if (filter.name == user.name) { 
          return true 
    } else { 
        return false 
      }  
    } else if (filter.address) { 
      if (filter.address == user.address) { 
        return true 
      } else { 
        return false 
      } 
    } else { 
      return true 
    } 
  } 
}

component.ts:

public filter: NewPin = new NewPin();

Why method added through decoration is not accessible Ask Question

Suppose that I have a Directive decorator which adds a static method to it’s target called factory:

function Directive<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
    static factory(...args): ng.IDirectiveFactory {
      const c: any = () => {
        return constructor.apply(this, args);
      };
      c.prototype = constructor.prototype;
      return new c(...args);
    }
  };
}

I also add the type via an interface:

interface BaseDirective extends ng.IDirective {
  factory(): ng.IDirectiveFactory;
}

Why in my class declaration of:

@Directive
class FocusedDirective implements BaseDirective {....

I get a Class 'FocusedDirective' incorrectly implements interface 'BaseDirective'.
Property 'factory' is missing in type 'FocusedDirective'.

Am I wrong to expect from @Directive to add this missing property for me?

Error with react-native JSX elements when using TypeScript Ask Question

I am creating an app using react-native and typescript.

I am facing following errors;

<AuthDetails
            style={{ marginTop: 60 }} // this line is giving error1.
            setUdaisId={this.setUdaisId}
            setPassword={this.setPassword}
          />

error1: [ts] Property ‘style’ does not exist on type ‘IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }>…’.

Similarly,

<TextInput
  underlineColorAndroid={'transparent'}
  secureTextEntry={true}
  placeholder = "Password"
  placeHolderStyle = {styles.placeHolderStyle} // this line is giving error2.
  style = {[styles.textInput, {marginTop:20}]}
/>

error2 : [ts] Property ‘placeHolderStyle’ does not exist on type ‘IntrinsicAttributes & IntrinsicClassAttributes> & …’.

And

  <Image
    style={styles.avatar}
    source={this.state.avatarSource}
    resizeMode={this.state.resizeMode} //this line gives error3.
/>

error3 : [ts]
Type ‘{ style: RegisteredStyle; source: any; resizeMode: string; }’ is not assignable to type ‘IntrinsicAttributes & IntrinsicClassAttributes> & Read…’.
Type ‘{ style: RegisteredStyle; source: any; resizeMode: string; }’ is not assignable to type ‘Readonly’.
Types of property ‘resizeMode’ are incompatible.
Type ‘string’ is not assignable to type ‘”center” | “stretch” | “cover” | “contain” | “repeat” | undefined’.

IDE shows error but Jest runs it without any issue Ask Question

I have written a unit test in Jest for a TypeScript function(checkEmail) that internally calls showAlert.

showAlert in the utils.ts:

export const showAlert = (message: string) => {
  toast(message);
};

And in my test case I have mocked the above function:

import {showAlert} from './utils'

showAlert = jest.fn()

Error

Although the test case works as expected, the IDE(in VSCode and WebStorm) shows error in the test file: Cannot assign to 'showAlert' because it is not a variable.

showAlert = jest.fn()
^^^^^^^^^

Any help to get rid of the above error would be greatly appreciated.

Usage of the showAlert:

function checkEmail(email: string) {
    if (!email.trim()) {
        showAlert('Email is required.');
    }
}

Repo to reproduce the issue: https://github.com/shishiranshuman13/tsjest-demo-error

How do I import scripts in inline web-worker Ask Question

So I have an inline web-worker (not in a separate file). I call .toString() on the methods I want as the worker, and convert them into a Blob. The blob is converted to a URL and passed to the web-worker.

I need ‘lodash’ inside of my web-worker, but I cannnot figure out how to inject it.

Lodash returns “” when calling toString(). I don’t want a seperate file for lodash so importScripts is not an option. Here is a snippet of my code:

interface IScript {
  name: string;
  value: Function;
}

interface IWorker {
  _shell: Worker;
  run(data?: any): Promise<any>;
  terminate(): void;
  subscribe(fn: Function): void;
  unsubscribe(fn: Function): void;
}

private _createWorker(fn: Function, otherScripts: IScript[] = []): IWorker {
  const blobArray = [...otherScripts, { name: 'onmessage', value: fn }]
    .map(script => `self.${script.name}=${script.value.toString()};`);

  const blob = new Blob(blobArray, { type: 'text/javascript' });
  const url = URL.createObjectURL(blob);

  ...

  const worker = new Worker(url);
  URL.revokeObjectURL(url);
}

Any suggestions would be greatly appreciated.