#ngrx/store-devtools - effects called twice - angular6

All actions I dispatch in effects are called twice. I already figured out, that this is caused by StoreDevtoolsModule. When I kick StoreDevtoolsModuleout of the app.module.ts my action will be called only once => everything is fine.
Here's my setup:
Angular 6.0.1
"#ngrx/effects": "6.0.0-beta.1",
"#ngrx/entity": "5.2.0",
"#ngrx/router-store": "6.0.0-beta.1",
"#ngrx/store": "6.0.0-beta.1",
"#ngrx/store-devtools": "6.0.0-beta.1",
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { StoreModule, Store, combineReducers, ActionReducerMap, MetaReducer }
from '#ngrx/store';
import { StoreDevtoolsModule } from '#ngrx/store-devtools';
import { EffectsModule } from '#ngrx/effects';
import { EquipmentModule } from './modules/equipment/equipment.module';
const reducers: ActionReducerMap<IAppState> = {
equipments: EquipmentReducer
};
#NgModule({
declarations: [
AppComponent
],
imports : [
BrowserModule,
StoreModule.forRoot(reducers),
StoreDevtoolsModule.instrument({
name: 'EQUIPMENT',
maxAge: 10,
logOnly: true,
}),
EquipmentModule,
EffectsModule.forRoot([]),
]
})
export class AppModule
{}
equipment.module.ts
import { EffectsModule } from '#ngrx/effects';
import { EquipmentEffects } from './equipment.effect';
import { EquipmentMockService } from './equipment.mock';
#NgModule({
imports: [
EffectsModule.forFeature([EquipmentEffects])
],
providers: [
{
provide: 'IEquipmentService',
useClass: EquipmentMockService
},
]
})
export class EquipmentModule {
}
equipment.effect.ts
import { CustomAction } from './../../custom.action';
import { Injectable, Inject } from '#angular/core';
import { Http } from '#angular/http';
import { Actions, Effect, ofType } from '#ngrx/effects';
import { Observable } from 'rxjs/Observable';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { EquipmentActions } from './equipment.action';
import { HttpClient } from '#angular/common/http';
import { Action, State } from '#ngrx/store';
import { of } from 'rxjs/internal/observable/of';
import { EquipmentService } from './equipment.service';
import { IAppState } from '../../app.state';
import { ofTypeWithPayload } from '../../customActionHelper';
#Injectable()
export class EquipmentEffects {
constructor(
private http: HttpClient,
private actions$: Actions,
private readonly state: State<IAppState>,
#Inject('IEquipmentService')
private equipmentService: EquipmentService
) { }
#Effect()
getAllEquipments$: Observable<Action> = this.actions$.pipe(
ofType(EquipmentActions.LOAD_ALL_EQUIPMENTS),
mergeMap(action => {
console.log('here'); <-- This console.log gets called twice!
return this.equipmentService.getAllEquipments().pipe(
map(equipments => ({ type: 'LOAD_ALL_EQUIPMENTS_SUCCESS', payload: equipments })),
catchError(() => of({ type: 'LOAD_ALL_EQUIPMENTS_FAIL' }))
);
}
)
);
Does anyone have an idea?
Thanks

Related

Why does the function run twice in my every component

I have this problem where i made three different components with routing. The problem is when i open my different components they loop twice at the moment i open them. What is causing this and how can i get rid of it?
Heres one example component which console.log runs twice when i open it.
import { Component, OnInit } from '#angular/core';
import nameData from '../../names/names.json'
interface INames {
name: string,
amount: number
}
const { names } = nameData
#Component({
selector: 'app-four',
templateUrl: './four.html',
styleUrls: ["./four.css"]
})
export class FourComponent {
nameArray: Array<INames> = names
constructor() {
}
hasName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa")
return this.nameArray.some(elem => elem.name === nameParam)
}
}
And here is the app.module.ts and app-routing.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './requirements/one/one';
import { TwoComponent } from './requirements/two/two';
import { ThreeComponent } from './requirements/three/three';
import { FourComponent } from './requirements/four/four';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header';
#NgModule({
declarations: [
AppComponent,
OneComponent,
TwoComponent,
ThreeComponent,
FourComponent,
HeaderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing-module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home/home';
import { FourComponent } from './requirements/four/four';
import { OneComponent } from './requirements/one/one';
import { ThreeComponent } from './requirements/three/three';
import { TwoComponent } from './requirements/two/two';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'one', component: OneComponent },
{ path: 'two', component: TwoComponent },
{ path: 'three', component: ThreeComponent },
{ path: 'four', component: FourComponent }
]
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I'm really confused why it loops the function as soon as i press the components button?
I do not recommand at all to use function in the HTML template, because they will be called everytime the Angular's change detection runs. Angular isn't able to tell if the result of the function will be different after each modification, si Angular will call the function everytime something change in the UI.
You must store the result of the function in a variable. Angular can check that the reference of the variable hasn't change.
You can read more information about it on this medium.
I recommend that you do the following
public fullName: string;
constructor() {
this.updateName();
}
private updateName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa");
this.fullName = this.nameArray.some(elem => elem.name === nameParam);
}
{{ fullName }}

Cannot use one of my element declared in my own library

I am trying to make a library that I can use a component from but angular says that the element I use is not recognized as an element. I am trying to export the VitalSignLinesListComponent.
The steps I follow are:
declare the component in the library module
export the component
in the library module
export the component in the public API
import the module from the library
place the element in the html
file
receive error
The error I am getting:
ERROR in src/app/app.component.html:2:1 - error NG8001:
'lib-vital-sign-lines-list' is not a known element: 1. If
'lib-vital-sign-lines-list' is an Angular component, then verify that
it is part of this module.
2. If 'lib-vital-sign-lines-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component
to suppress this message.
COMPONENT:
#Component({
selector: 'lib-vital-sign-lines-list',
templateUrl: './vital-sign-lines-list.component.html',
styleUrls: ['./vital-sign-lines-list.component.css']
})
export class VitalSignLinesListComponent implements OnInit {
#Input()
idEdDossier: string;
}
LIBRARY MODULE:
import { NgModule } from '#angular/core';
import { VitalsignsComponent } from './vitalsigns.component';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { RouterModule, Routes } from '#angular/router';
import { ModalInputComponent } from './modal-input/modal-input.component';
import { VitalSignLinesListComponent } from './vital-sign-lines-list/vital-sign-lines-list.component';
import { NgSelectModule } from '#ng-select/ng-select';
import { FormsModule } from '#angular/forms';
import { EcareLibModule } from 'ecarelib'
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { ComboBoxComponent } from './combo-box/combo-box.component';
import { ComboBoxPipe } from './combo-box/combo-box.pipe';
import { LogService } from './services/log.service';
import { ClickOutsideDirective } from './vital-sign-lines-list/click-outside.directive';
const appRoutes: Routes = [
{ path: 'modal', component: ModalInputComponent },
{ path: 'vitalSignLinesList', component: VitalSignLinesListComponent }
];
// #dynamic
#NgModule({
declarations: [
VitalsignsComponent,
ModalInputComponent,
VitalSignLinesListComponent,
ComboBoxComponent,
ComboBoxPipe,
ClickOutsideDirective
],
imports: [
BrowserModule,
HttpClientModule,
EcareLibModule.forRoot(),
NgSelectModule,
RouterModule.forRoot(appRoutes, { enableTracing: false }),
FormsModule,
NgbModule
],
providers: [LogService],
exports: [VitalsignsComponent, VitalSignLinesListComponent]
})
export class VitalsignsModule {
}
PUBLIC-API:
export * from './lib/vitalsigns.service';
export * from './lib/vitalsigns.component';
export * from './lib/vitalsigns.module';
export * from './lib/vital-sign-lines-list/vital-sign-lines-list.component';
IMPORT LIBRARY: (VitalsignsModule)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { NgSelectModule } from '#ng-select/ng-select';
import { FormsModule } from '#angular/forms';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { AppComponent } from './app.component';
import { HttpClientModule } from '#angular/common/http';
import { RouterModule, Routes } from '#angular/router';
import { EcareLibModule } from 'ecarelib';
import { VitalsignsModule } from 'vitalsigns';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
EcareLibModule.forRoot(),
HttpClientModule,
RouterModule.forRoot([]),
VitalsignsModule,
NgbModule,
NgSelectModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
HTML:
<lib-vital-sign-lines-list [idEdDossier]=idDossier></lib-vital-sign-lines-list>

Uncaught ReferenceError: Cannot access 'MaterialModule' before initialization

I am working on a simple form for a personal project and try to put a phone form use this example: https://material.angular,.io/components/form-field/examples and after that fits everything it gives me this error and although Remove everything related to the phone form remains the same.
form.component.ts
import { Component, OnInit } from '#angular/core';
import { Builder } from 'protractor';
import {FocusMonitor} from '#angular/cdk/a11y';
import {coerceBooleanProperty} from '#angular/cdk/coercion';
import {ElementRef, Input, OnDestroy, Optional, Self} from '#angular/core';
import {FormBuilder, FormGroup, ControlValueAccessor, NgControl} from '#angular/forms';
import {MatFormFieldControl} from '#angular/material';
import {Subject} from 'rxjs';
#Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss'],
providers: [{provide: MatFormFieldControl, useExisting: MyTelInput}],
host: {
'[class.example-floating]': 'shouldLabelFloat',
'[id]': 'id',
'[attr.aria-describedby]': 'describedBy',
}
})
export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyTel>, OnDestroy {
static nextId = 0;
parts: FormGroup;
stateChanges = new Subject<void>();
focused = false;
errorState = false;
controlType = 'example-tel-input';
id = `example-tel-input-${MyTelInput.nextId++}`;
describedBy = '';
onChange = (_: any) => {};
onTouched = () => {};
get empty() {
const {value: {area, exchange, subscriber}} = this.parts;
return !area && !exchange && !subscriber;
}
get shouldLabelFloat() { return this.focused || !this.empty; }
#Input()
get placeholder(): string { return this._placeholder; }
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder: string;
#Input()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
private _required = false;
#Input()
get disabled(): boolean { return this._disabled; }
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
this._disabled ? this.parts.disable() : this.parts.enable();
this.stateChanges.next();
}
private _disabled = false;
#Input()
get value(): MyTel | null {
const {value: {area, exchange, subscriber}} = this.parts;
if (area.length === 3 && exchange.length === 3 && subscriber.length === 4) {
return new MyTel(area, exchange, subscriber);
}
return null;
}
set value(tel: MyTel | null) {
const {area, exchange, subscriber} = tel || new MyTel('', '', '');
this.parts.setValue({area, exchange, subscriber});
this.stateChanges.next();
}
constructor(
formBuilder: FormBuilder,
private _focusMonitor: FocusMonitor,
private _elementRef: ElementRef<HTMLElement>,
#Optional() #Self() public ngControl: NgControl) {
this.parts = formBuilder.group({
area: '',
exchange: '',
subscriber: '',
});
_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this.focused && !origin) {
this.onTouched();
}
this.focused = !!origin;
this.stateChanges.next();
});
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
ngOnDestroy() {
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}
setDescribedByIds(ids: string[]) {
this.describedBy = ids.join(' ');
}
onContainerClick(event: MouseEvent) {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this._elementRef.nativeElement.querySelector('input')!.focus();
}
}
writeValue(tel: MyTel | null): void {
this.value = tel;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
_handleInput(): void {
this.onChange(this.parts.value);
}
}
export class MyTel {
constructor(public area: string, public exchange: string, public subscriber: string) {}
}
export class FormComponent implements OnInit {
public formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
name: '',
lastname: '',
option: '',
checkbox: '',
masculino: '',
femenino: '',
email:'',
});
}
}
form.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormRoutingModule } from './form-routing.module';
import { FormComponent } from './form/form.component';
import { MaterialModule } from '../material/material.module';
import { FormBuilder } from '#angular/forms';
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule,
FormRoutingModule,
MaterialModule
],
providers: [
FormBuilder
]
})
export class FormModule { }
material.module.ts
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
import { ReactiveFormsModule } from '#angular/forms';
import { FormModule } from '../form/form.module';
import { FormComponent } from '../form/form/form.component';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
ReactiveFormsModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
FormModule,
FormComponent,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '#angular/platform-browser/animations';
import { MaterialModule } from './modules/material/material.module';
import { MatSelectModule, MatInputModule, MatCheckbox, MatRadioModule } from '#angular/material';
import { MatFormFieldModule } from '#angular/material/form-field';
import { FormModule } from './modules/form/form.module';
import { FormComponent } from './modules/form/form/form.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule,
MatSelectModule,
MatInputModule,
MatFormFieldModule,
MatRadioModule,
FormModule,
FormComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
form-routing.component.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FormComponent } from './form/form.component';
const routes: Routes = [{path: '', component: FormComponent}];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FormRoutingModule { }
Please help
you have 2 major errors here:
importing a component to a module. Can't be done, only modules can be imported. Components can be declared and exported. This is causing the error you're seeing.
Circular module imports by importing FormModule to MaterialModule and vice versa. Can't do it. Imports can only go in one direction. This is causing the warning you're seeing which is actually an error preventing you from recompiling.
And some minor errors, like you're mixing up module logic and double importing modules
fixes below....
material module, let it do what it's supposed to do, import and export material modules, NOTHING ELSE, remover reactive forms import, remove circular reference to FormsModule, remove form component import:
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
form module, import the reactive forms module here (dont provide the form builder), export your forms component to use it in other modules:
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule, // if you have a common module, you could import / export the reactive forms module there if it's more appropriate and then you don't need to import it again here.
FormRoutingModule,
MaterialModule,
ReactiveFormsModule // do this here, don't provide the form builder
],
exports: [
FormComponent // if you want to use this component in other modules, export here and import the MODULE
]
})
export class FormModule { }
app module, don't try to import the form component, just the module. Don't reimport material modules, you do that in the material module:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule, // do you really NEED the material module here?
FormModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

router navigation not working after login success

angular router not working after login success.
I have Auth Module
Under Auth module i have login components
I have Admin Module
Under Admin module i have 3 components
1).admin component
2).admin-dashboard
3).blog component
In admin.component.html
written (router-outlet) tag.
//getting login success and userdata
{"result":"success","UserId":"U-001","UserName":"Super Admin","UserEmail":"admin#dw.com"}
if result is success trying redirecting to admin component. but it is not working.
please check the code.where i did the mistake?.
Thanks in advance.
app.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
//import { PreloadAllModules } from '#angular/router';
import { CustomPreloadingStrategyService } from './custom-preloading-strategy.service';
import { CustomPreloadingWithDealyStrategyService } from './custom-preloading-with-delay-strategy.service';
const routes: Routes = [
{
path:'',redirectTo:'/login',pathMatch:'full'
},
{
path:'**',component:PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes,
{
preloadingStrategy:CustomPreloadingWithDealyStrategyService
})],
providers: [CustomPreloadingStrategyService,CustomPreloadingWithDealyStrategyService],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
import { BrowserModule, Title } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AlertModule } from 'ngx-bootstrap';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { DragDropModule } from '#angular/cdk/drag-drop';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { MatToolbarModule, MatFormFieldModule, MatDatepickerModule, MatNativeDateModule, MatInputModule } from '#angular/material';
import { HeaderComponent } from './header/header.component';
import { AuthService } from './auth/auth.service';
import { AdminModule } from './admin/admin.module';
import { AuthModule } from './auth/auth.module';
import { httpInterceptorProviders } from './http-interceptors/index';
#NgModule({
declarations: [
AppComponent,
PageNotFoundComponent, HeaderComponent ],
imports: [
BrowserModule,
DragDropModule,
FormsModule,
ReactiveFormsModule,
AlertModule.forRoot(),
BrowserAnimationsModule,
HttpClientModule,
MatToolbarModule,
MatFormFieldModule,
MatInputModule,
MatDatepickerModule,
MatNativeDateModule,
AdminModule,
AuthModule,
AppRoutingModule],
exports: [MatToolbarModule, MatFormFieldModule, MatInputModule, MatDatepickerModule, MatNativeDateModule,AdminModule,AuthModule],
providers: [Title, AuthService,httpInterceptorProviders],
bootstrap: [AppComponent]
})
export class AppModule {
constructor ()
{
console.log('App Module load');
}
}
admin.routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AdminComponent } from './admin/admin.component';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';
import { BlogsComponent } from './blogs/blogs.component';
import { AuthGuard } from '../auth/auth.guard';
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
children: [
{ path: 'blogs', component: BlogsComponent },
{ path: '', component: AdminDashboardComponent }
],
}
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
providers: [],
exports: [RouterModule]
})
export class AdminRoutingModule { }
admin.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ReactiveFormsModule } from '#angular/forms';
import { AdminRoutingModule } from './admin-routing.module';
import { AdminComponent } from './admin/admin.component';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';
import { BlogsComponent } from './blogs/blogs.component';
#NgModule({
declarations: [AdminComponent, AdminDashboardComponent, BlogsComponent],
imports: [
CommonModule,ReactiveFormsModule,AdminRoutingModule
]
})
export class AdminModule { }
login.component.ts
import { Component, OnInit } from '#angular/core';
import { Route, Router } from '#angular/router';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { AuthService } from '../auth.service';
import { Loginuser } from './loginuser';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
submitted = false;
LoginForm:FormGroup;
SuccessAlert : string;
WarningAlert : string;
showSuccessAlert = false;
showWarningAlert = false;
isLoggedIn : boolean
constructor(private router:Router,private fb: FormBuilder, private authservice: AuthService)
{
this.LoginForm = fb.group({
emailid: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(8)])],
})
}
ngOnInit() {
this.authservice.logout();
}
LogInUser(){
let login = this.LoginForm.value;
this.checklogin(login);
}
checklogin(loginUser: Loginuser){
this.authservice.userlogin(loginUser).subscribe(
data =>{
if(data["result"]=="success"){
this.showSuccessAlert = true;
this.SuccessAlert = data["result"];
this.LoginForm.reset();
localStorage.setItem("currentUser", JSON.stringify(data));
this.isLoggedIn = true;
this.router.navigate(['/admin']);
}
else
{
this.showWarningAlert = true;
this.WarningAlert = data["result"];
}
}
)
}
}
auth.guard.ts
import { Injectable } from '#angular/core';
import { CanActivate, CanActivateChild, CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '#angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
#Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router, private authservice: AuthService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
if(this.authservice.isLoggedIn) {
return true
}
else
{
return false
this.router.navigate(['/login']);
}
}
canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.canActivate(next, state);
}
}
The problem is the router.navigate that does not redirect.
Test the following codes to resolve your issue:
this.router.navigate(["../admin"]);
or
this.router.navigateByUrl('/admin');
this is worked for me.
import { Location } from '#angular/common';
import { Router } from '#angular/router';
this.location.replaceState('/');
this.router.navigate(['home']);
this.location.replaceState
for replace history instead of pushing so if the user goes back it won’t go back to the url that the user was on, but the one before.
router.navigate will not work directly because queryParams is Observable, so you cannot get parameters from it in this way.
Try this
this.router.navigate['../admin']

ERROR Error: StaticInjectorError(AppModule)[StorieControllerComponent -> DataService]:

I am getting this error and I already check all the import and Modules.
I am trying to access to a JSON file inside my project and use that data in an object but I not sure what is the problem here. I have my object well define with my JSON and I am not sure that the problem is with the Http
This is the Error that I am getting in the console:
This is the Service
import { storiesStatus } from './stories';
import { Injectable } from '#angular/core';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { Headers, Http, Response, HttpModule} from '#angular/http';
const storiesJson = './../json/stories_data_json.json';
#Injectable()
export class DataService {
constructor(private http: Http) { }
getStoriesData(): Promise<storiesStatus[]> {
return this.http.get(storiesJson)
.toPromise()
.then(response => response.json() as storiesStatus[])
.catch();
}
}
This is my App Module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import * as Hammer from 'hammerjs';
import 'hammer-timejs';
import { HammerGestureConfig, HAMMER_GESTURE_CONFIG } from
'#angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '#angular/router';
import { ChartsModule } from 'ng2-charts';
import { AppComponent } from './app.component';
import { AppChildModule } from './modules/app-child.module';
import { CheckinComponent } from
'./modules/controllers/checkin/checkin.component';
import { PicturePostComponent } from './modules/controllers/picture-
post/picture-post.component';
import { StorieControllerComponent } from './modules/controllers/storie-
controller/storie-controller.component';
import { LoginComponent } from './modules/screens/login/login.component';
import { router } from './modules/routing/app-routing.module';
import { FeedComponent } from './modules/screens/home/feed/feed.component';
import { HomeComponent } from './modules/screens/home/home.component';
import { WelcomeComponent } from
'./modules/screens/welcome/welcome.component';
import { SignupComponent } from './modules/screens/signup/signup.component';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule } from '#angular/http';
import { BrowserAnimationsModule } from '#angular/platform-
browser/animations';
export class MyHammerConfig extends HammerGestureConfig {
overrides = <any>{
'swipe': { direction: Hammer.DIRECTION_ALL }
}
}
#NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
WelcomeComponent,
SignupComponent
],
imports: [
BrowserModule,
HttpClientModule,
HttpModule,
AppChildModule,
ChartsModule,
BrowserAnimationsModule,
router
],
providers: [{
provide: HAMMER_GESTURE_CONFIG,
useClass: MyHammerConfig
}],
bootstrap: [AppComponent]
})
export class AppModule { }
This is my component conected to the service:
import { DataService } from '../../../../assets/services/data.service';
import { storiesStatus } from '../../../../assets/services/stories';
import { Component, OnInit } from '#angular/core';
import { NgModule } from '#angular/core';
import { Headers, Http, Response, HttpModule} from '#angular/http';
#Component({
selector: 'app-storie-controller',
templateUrl: './storie-controller.component.html',
styleUrls: ['./storie-controller.component.css']
})
#NgModule({
declarations: []
})
export class StorieControllerComponent implements OnInit {
public stories: storiesStatus[];
constructor(private data: DataService) {
this.stories = [];
}
ngOnInit() {
this.data.getStoriesData().then(storiesRes => console.log(
this.stories = storiesRes));
}
}
In your app.module you forgot to add DataService to your provider array