ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a function at eval (ngx-toastr.js?4996:264) - ngx-toastr

I am using ngx-toastr in angular 6 for http error notification, as injected ToastrService in httpInterceptor
export class MyInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
tap((evt: any) => {
if (evt instanceof HttpResponse) {
if (evt.body)
this.toasterService.success('success', '!!', { positionClass: 'toast-bottom-center' });
//alert(`success`);
}
}),
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
try {
this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
} catch (e) {
this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
}
//log error
}
return of(err);
})
)
}
}
and imported ToastrModule in app.module.ts like
imports:[
ToastrModule.forRoot()
]
I am getting below error, any idea whats going wrong here..............
ngx-toastr.js?4996:264 Uncaught TypeError: Object(...) is not a
function
at eval (ngx-toastr.js?4996:264) .................................

I found the actual issue regarding this. It's happening because of the mismatch of the version of an angular and the package. To overcome this problem perform the following steps
STEP1: Check for angular CLI version: ng --version
Now check this image
If your angular version is 7.3.10 then you need to install 10.1.0 version of ngx-toastr
STEP2: Install a specific version of ngx-toastr according to your angular CLI version: npm i ngx-toastr#10.1.0 --save
STEP3: import it into app.module.ts
app.module.ts
import { CommonModule } from '#angular/common';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
#NgModule({
imports: [
CommonModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot() // ToastrModule added
],
bootstrap: [App],
declarations: [App]
})
export class AppModule {}
STEP4: add css path in styles array in angular.json file
angular.json
"styles": [
"node_modules/font-awesome/css/font-awesome.css",
"src/styles/app.scss",
"node_modules/sweetalert2/dist/sweetalert2.min.css",
"node_modules/ngx-toastr/toastr.css"
]
Don't forget to restart your server after making changes in angular.json file
STEP5: make helper service to show toasters
helper.service.ts
import { Injectable } from '#angular/core';
import { ToastrService } from 'ngx-toastr';
#Injectable({
providedIn: 'root'
})
export class HelperService {
constructor(private toastr: ToastrService) { };
showSuccessToast(msg) {
this.toastr.success(msg);
}
showErrorToast(msg) {
this.toastr.error(msg);
}
showInfoToast(msg) {
this.toastr.info(msg);
}
}
STEP6: Now you are done you just need to use these functions in your component.ts file
user.component.ts
import { Component, OnInit } from '#angular/core';
import { routerTransition } from '../../router.animations';
import { UserService } from './user.service';
import { HelperService } from 'src/app/helpers/helper.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss'],
animations: [routerTransition()]
})
export class UserComponent implements OnInit {
constructor(
private userService: UserService,
private helperService: HelperService,
) {
}
ngOnInit() {
this.getUsers();
}
async getUsers() {
try {
const res: any = await this.userService.getUsers();
this.helperService.showSuccessToast(res.message);
} catch (err) {
this.helperService.showErrorToast(err.error || 'Something went wrong');
}
}
}

Related

Angular 13 running jest error "Unexpected value 'MatTimepickerModule' imported by the module 'DynamicTestModule'. Please add an #NgModule annotati."

I am getting the below error when running karma from angular using the command :
npm run test-headless
FAIL src/app/req-form-body/req-form-body.component.spec.ts (26.126 s)
● ReqFormBodyComponent › should create
**Unexpected value 'MatTimepickerModule' imported by the module 'DynamicTestModule'. Please add an #NgModule annotation.**
49 |
50 | beforeEach(() => {
> 51 | fixture = TestBed.createComponent(ReqFormBodyComponent);
| ^
52 | component = fixture.componentInstance;
53 | fixture.detectChanges();
54 | });
at verifySemanticsOfNgModuleDef (node_modules/#angular/core/fesm2015/core.mjs:23854:19)
at node_modules/#angular/core/fesm2015/core.mjs:23865:9
at Array.forEach (<anonymous>)
at verifySemanticsOfNgModuleDef (node_modules/#angular/core/fesm2015/core.mjs:23863:60)
at Function.get (node_modules/#angular/core/fesm2015/core.mjs:23825:21)
at R3TestBedCompiler.applyProviderOverridesToModule (node_modules/#angular/core/fesm2015/testing.mjs:1067:29)
at R3TestBedCompiler.compileTestModule (node_modules/#angular/core/fesm2015/testing.mjs:1315:14)
at R3TestBedCompiler.finalize (node_modules/#angular/core/fesm2015/testing.mjs:921:14)
at TestBedRender3.get testModuleRef [as testModuleRef] (node_modules/#angular/core/fesm2015/testing.mjs:1796:49)
at TestBedRender3.inject (node_modules/#angular/core/fesm2015/testing.mjs:1719:29)
at TestBedRender3.createComponent (node_modules/#angular/core/fesm2015/testing.mjs:1759:44)
at Function.createComponent (node_modules/#angular/core/fesm2015/testing.mjs:1617:37)
at src/app/req-form-body/req-form-body.component.spec.ts:51:23
at _ZoneDelegate.Object.<anonymous>._ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:409:30)
at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3803:43)
at _ZoneDelegate.Object.<anonymous>._ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:408:56)
at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:169:47)
at Object.wrappedFunc (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:4288:34)
//and here is my ReqFormBodyComponent.spec.ts file .
enter code hereimport { ComponentFixture, TestBed } from '#angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { FormBuilder, FormControl, FormGroup, Validators } from '#angular/forms';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { MaterialModule } from './../../app/shared/material';
import { ReqFormBodyComponent } from './req-form-body.component';
import { MatTimepickerModule } from 'mat-timepicker';
import _moment from 'moment';
import { default as _rollupMoment } from 'moment';
const moment = _rollupMoment || _moment;
export const DATE_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'DD-MMM-YYYY',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
};
describe('ReqFormBodyComponent', () => {
let component: ReqFormBodyComponent;
let fixture: ComponentFixture<ReqFormBodyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FormsModule, ReactiveFormsModule, MaterialModule, BrowserAnimationsModule, MatTimepickerModule],
declarations: [],
providers: [FormBuilder],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ReqFormBodyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
//corresponding component file (ReqFormBodyComponent.ts)
import { StepperSelectionEvent } from '#angular/cdk/stepper';
import { AfterViewInit, ChangeDetectionStrategy, Component,
ElementRef, OnInit, ViewChild } from '#angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from
'#angular/forms';
import { MatStepper } from '#angular/material/stepper';
import { MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '#angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '#angular/material/core';
import _moment from 'moment';
import { default as _rollupMoment } from 'moment';
const moment = _rollupMoment || _moment;
export const DATE_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'DD-MMM-YYYY',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
};
#Component({
selector: 'ereq-req-form-body',
templateUrl: './req-form-body.component.html',
styleUrls: ['./req-form-body.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS] },
{ provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS },
],
})
export class ReqFormBodyComponent implements OnInit, AfterViewInit {
#ViewChild('stepper') public stepper: MatStepper;
public isLinear = false;
public totalStepCount: number;
public selectedStep: string;
public firstFormGroup: FormGroup;
public secondFormGroup: FormGroup;
public thirdFormGroup: FormGroup;
public fourthFormGroup: FormGroup;
public fifthFormGroup: FormGroup;
public sixthFormGroup: FormGroup;
public lastFormGroup: FormGroup;
public date = new FormControl(moment());
public defaultValue = { hour: 13, minute: 30 };
constructor(private formBuilder: FormBuilder) {}
public ngOnInit(): void {...
Your angular13 TestBed did not find an ivy compatible library to load by jest.
You can work around this by
Step: make sure you have the correct ngcc build in the package's
node_module folder.
Step: Add a moduleMapper for jest for the built
package

Ionic4: Phonegap-nfc: where is the content?

VERSION: Ionic 4
Plugin: phonegap-nfc
Hi everyone!
I'm trying to use this plugin (https://ionicframework.com/docs/native/nfc) and following the instructions, I should be able to read a message sent from another NFC device. The event is fired and I know something is sent, but I'm not able to understand what and where the message is stored.
This is the code:
home.page.ts
import { Component } from '#angular/core';
import {Ndef, NFC} from '#ionic-native/nfc/ngx';
import {AlertController} from '#ionic/angular';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private nfc: NFC, private ndef: Ndef, private alertController: AlertController) { }
readNFC() {
this.nfc.addNdefListener(() => {
this.presentAlert('ok');
}, (err) => {
this.presentAlert('ko' + err);
}).subscribe((event) => {
console.log(event);
console.log(JSON.stringify(event));
this.presentAlert('Il messaggio contiene' + event.tag + ' ' + this.nfc.bytesToHexString(event.tag.id));
});
}
writeNFC() {
this.nfc.addNdefListener(() => {
console.log('successfully attached ndef listener');
const message = this.ndef.textRecord('Hello world');
this.nfc.share([message]).then(
value => {
this.presentAlert('ok');
}
).catch(
reason => {
this.presentAlert('ko');
}
);
}, (err) => {
this.presentAlert('ko' + err);
});
}
async presentAlert(mess) {
const alert = await this.alertController.create({
header: 'attenzione',
message: mess,
buttons: ['OK']
});
await alert.present();
}
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {Ndef, NFC} from '#ionic-native/nfc/ngx';
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
NFC,
Ndef
],
bootstrap: [AppComponent]
})
export class AppModule {}
This is the stringify obtained by printing the content of event:
{"isTrusted":false,"tag":{"id":[0],"techTypes":["android.nfc.tech.Ndef"],"type":"android.ndef.unknown","maxSize":0,"isWritable":false,"ndefMessage":[{"tnf":1,"type":[85],"id":[],"payload":[3,112,108,97,121,46,103,111,111,103,108,101,46,99,111,109,47,115,116,111,114,101,47,97,112,112,115,47,100,101,116,97,105,108,115,63,105,100,61,99,111,109,46,119,97,107,100,101,118,46,119,100,110,102,99,38,102,101,97,116,117,114,101,61,98,101,97,109]},{"tnf":4,"type":[97,110,100,114,111,105,100,46,99,111,109,58,112,107,103],"id":[],"payload":[99,111,109,46,119,97,107,100,101,118,46,119,100,110,102,99]}],"canMakeReadOnly":false}}
Thanks in advance for your help!
Your data is at
ndefMessage[0].payload
you need to use
nfc.bytesToString()
the payload to convert to string

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked in HTTP loading interceptor

Goal:
Im trying to show a loading icon on every ajax call.To this end, I added an HTTP interceptor which sets a variable to true when one or more requests are ongoing and to false when all have completed. The UI tests for this value and shows a loader or not, depending.
Problem:
On every ajax call, an error is thrown:
ExpressionChangedAfterItHasBeenCheckedError:
Expression has changed after it was checked.
Previous value: 'ngIf: [object Object]'. Current value: 'ngIf: true'.
Simplified Stakckblitz with reproducible error:
https://stackblitz.com/edit/angular-h4rpfb
Code:
appcomponent.html:
<p *ngIf="loaderService.isLoading | async">
Loading!
</p>
<p *ngIf="!(loaderService.isLoading | async)">
Not Loading!
</p>
<button (click)="loadSomething()">Load Something</button>
{{matches|async}}
appcomponent.ts:
import { Component } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { LoaderService } from "./core";
import { Observable } from "rxjs";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
matches: Observable<any>;
constructor(public loaderService: LoaderService, private http: HttpClient) {}
loadSomething() {
this.matches = this.http.get("https://jsonplaceholder.typicode.com/posts");
}
}
loader.interceptor.ts:
import { Injectable } from '#angular/core';
import {
HttpErrorResponse,
HttpResponse,
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { LoaderService } from './loader.service';
#Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
console.log(i, this.requests.length);
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
this.loaderService.isLoading.next(true);
return Observable.create(observer => {
const subscription = next.handle(req)
.subscribe(
event => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
err => { this.removeRequest(req); observer.error(err); },
() => { this.removeRequest(req); observer.complete(); });
// teardown logic in case of cancelled requests
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
});
}
}
loader.service.ts:
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class LoaderService {
public isLoading = new BehaviorSubject(false);
constructor() {}
}
Ok I got it to work by adding this to the component with the loader:
changeDetection: ChangeDetectionStrategy.OnPush
So the appcomponent.html now looks like this:
import { Component,ChangeDetectionStrategy } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { LoaderService } from "./core";
import { Observable } from "rxjs";
#Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
matches: Observable<any>;
constructor(public loaderService: LoaderService, private http: HttpClient) {}
loadSomething() {
this.matches = this.http.get("https://jsonplaceholder.typicode.com/posts");
}
}
Example:
https://stackblitz.com/edit/angular-n6fzjm

Nativescript angular - module that contains dataform exits in ios without error! lazy loading module

I am developing nativescript-angular app that contains dataform in a module and calling this module using in lazy loading technique. Life is beautiful in Android, but the application exits immediately when I open this module in ios wihtout any error log!
The code is very simple and forward, I can't see where is the problem!
test.component.ts
import { Component, OnInit } from "#angular/core";
import { ActivatedRoute } from "#angular/router";
import { RadDataForm, DataFormEventData } from "nativescript-ui-dataform";
import { UserAddress } from "../../shared/data-services/address";
#Component({
selector: "test",
moduleId: module.id,
templateUrl: "./test.component.html",
styleUrls:["./test.component.css"]
})
export class TestComponent implements OnInit {
private _userAddress: UserAddress;
constructor() {
}
ngOnInit() {
this._userAddress = new UserAddress();
}
get userAddress(): UserAddress {
return this._userAddress;
}
}
test.component.html
<ActionBar class="action-bar">
<NavigationButton [nsRouterLink]="['../../home']" android.systemIcon="ic_menu_back"></NavigationButton>
<Label class="action-bar-title" text="Test"></Label>
</ActionBar>
<ScrollView tkExampleTitle tkToggleNavButton>
<StackLayout>
<RadDataForm tkExampleTitle tkToggleNavButton [source]="userAddress">
</RadDataForm>
</StackLayout>
</ScrollView>
Routing of this module
signup-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { ItemsComponent } from "./test/test.component";
export const COMPONENTS = [ItemsComponent ];
const routes: Routes = [
{ path: "", redirectTo: "testInfo" },
{ path: "testInfo", component: testComponent }
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)], // set the lazy loaded routes using forChild
exports: [NativeScriptRouterModule]
})
export class SignupRoutingModule {}
Then we have
signup.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { COMPONENTS, SignupRoutingModule } from "./signup-routing.module";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NativeScriptUIDataFormModule } from "nativescript-ui-dataform/angular";
#NgModule({
imports: [
NativeScriptCommonModule, // for rednering actionbar with lazy laoding
NativeScriptFormsModule,
SignupRoutingModule,
NativeScriptUIDataFormModule
],
declarations: [
...COMPONENTS
],
// providers: [SignupService],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class SignupModule { }
And the module is called using lazy loading in the basic routing file like this:
{ path: "signup", loadChildren: "~/app/signup/signup.module#SignupModule", outlet: "homeTab" }
Help is appreciated!
CODE ON GitHub
https://github.com/lighttiger/lazy

angular 5 State management using Redux and Behavior Subject

How do you do state management in angular 5 ? Between Redux and Behavior Subject which approach is better to follow and why.
Thanks.
Angular Service Layers: Redux, RxJs and Ngrx Store - When to Use a Store And Why?
ngrx sample example
Install the below packages:
npm install #ngrx/store --save
npm install #ngrx/effects --save
app.module.ts
import { appReducer } from './state/app.reducer';
import { StoreModule } from '#ngrx/store';
#NgModule({
declarations: [
...
],
imports: [
...
StoreModule.forRoot(appReducer)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Store } from '#ngrx/store';
import { AppState } from './state/app.state';
import { SetAppTitleAction, getAppTitle } from './state/app-title';
import { Observable } from 'rxjs';
#Component({
selector: 'app-root',
template:
`<h1>{{appTitle$ | async}}</h1>
`
})
export class AppComponent implements OnInit {
appTitle$: Observable<string>;
constructor(private store: Store<AppState>) {
this.appTitle$ = this.store.select(getAppTitle);
}
ngOnInit(): void {
this.store.dispatch(new SetAppTitleAction('Location: AppComponent'));
}
}
app-title.action.ts
import { Action } from '#ngrx/store';
export const SetAppTitle = 'Set App Title';
export class SetAppTitleAction implements Action {
readonly type = SetAppTitle;
constructor(public payload: string) {}
}
export type AppTitleActions = SetAppTitleAction;
app-title.reducer.ts
import { AppTitleActions, SetAppTitle } from './app-title.actions';
export function appTitleReducer(state: string, action: AppTitleActions) {
switch (action.type) {
case SetAppTitle:
return action.payload;
default: return state;
}
}
index.ts
export * from './app-title.actions';
import { AppState } from './app.state';
export const getState = (state: AppState) => state;
export const getAppTitle = createSelector(getState, state => state.appTitle);
app.reducer.ts
import { ActionReducerMap } from '#ngrx/store';
import { AppState } from './app.state';
import { appTitleReducer } from './app-title/app-title.reducer';
import { versionInfoReducer } from './version-info/version-info.reducer';
export const appReducer: ActionReducerMap<AppState> = {
appTitle: appTitleReducer
};
export interface AppState {
appTitle: string;
}