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
Related
Im having an error where it wont implement the interface, ive tried fixing it but it wont.
i have been sitting on this problem for days and have tried all sorts of methods but i just cant seem to crack it.
Sourcecode:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import {HttpClientModule} from '#angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '#angular/forms';
import { FrontpageComponent } from './frontpage/frontpage.component';
import { AdministratorComponent } from './administrator/administrator.component';
import { AdminCustomerComponent } from './admin-customer/admin-customer.component';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { DatePipe } from '#angular/common';
import { CategoryComponent } from './category/category.component';
import { BookComponent } from './book/book.component';
import { LoginComponent } from './login/login.component';
import { ContactComponent } from './contact/contact.component';
import { CategoryDetailsComponent } from './category-details/category-details.component';
import { BookDetailsComponent } from './book-details/book-details.component';
import { LoanComponent } from './loan/loan.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {MatDatepickerModule} from '#angular/material/input';//error happens here
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
Ng2SearchPipeModule,
BrowserAnimationsModule,
MatDatepickerModule,//and here
],
providers: [DatePipe],
bootstrap: [AppComponent]
})
export class AppModule { }
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>
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']
Hello I am trying to import http call from '#angular/common/http' and am getting error message that module has no exported member 'http'
Error:[ts] Module '"e:/car/node_modules/#angular/common/http"' has no exported member 'Http'. [2305]
import {
RouterModule
} from '#angular/router';
import {
BrowserModule
} from '#angular/platform-browser';
import {
NgModule
} from '#angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
HomeComponent
} from './home/home.component';
import {
HttpClientModule
} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([{
path: '',
component: HomeComponent
}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
import {
Http
} from '#angular/common/http';
import {
Component,
OnInit
} from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) {}
products = [];
fetchData = function() {
this.http.get('http://localhost:5555/products').subscribe(
(res: Response) => {
this.products = res.json();
}
);
};
ngOnInit() {
this.fetchData();
}
}
the below code is used for inserting json file which includes the details
HttpClientModule will inject HttpClient service not the Http.
Please use HttpClient in constructor injection in the HomeComponent.
constructor(private http: HttpClient) {}
For Reference created sample stackblitz code.
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