ngx-translation issue with ionic 3 app - json

ngx translation with ionic 3 app not working for me. below is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule,Http } from '#angular/http';
import { IonicStorageModule } from '#ionic/storage';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { MyApp } from './app.component';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
export function createTranslateLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
declarations: [
MyApp
],
imports: [
BrowserModule,
HttpModule,
IonicStorageModule.forRoot(),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
}),
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {}
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Storage } from '#ionic/storage';
import { TranslateService } from '#ngx-translate/core';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
public rootPage: any;
constructor(public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
public storage: Storage,
public translate: TranslateService) {
this.storage.get('AppLangcode')
.then((AppLangcode) => {
if(AppLangcode==null){
translate.setDefaultLang('en');
}else{
translate.setDefaultLang(AppLangcode);
}
})
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.menu.swipeEnable(false);
});
}
}
In above file i am checking storage preference in local db and then set it to default language on load application.
My RootPage home.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
declarations: [
HomePage,
],
imports: [
IonicPageModule.forChild(HomePage),
TranslateModule.forChild()
],
exports: [
HomePage
]
})
export class HomePageModule {}
home.ts
import { Component} from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '#ionic/storage';
import { TranslateService } from '#ngx-translate/core';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public navParams: NavParams,
public storage: Storage,
public translate: TranslateService,) {
}
ionViewDidLoad() {
//console.log('ionViewDidLoad HomePagePage');
}
}
home.html
<ion-header>
<ion-navbar color='navbarColor'>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
</ion-navbar>
</ion-header>
<ion-content class="grid-basic-page">
<ion-grid>
<ion-row>
<ion-col (click)="openPage('QuickBookPage');">
<div><img src="assets/icon/icon-book-cylinder.png">{{"quick_book_pay" | translate}}</div>
</ion-col>
<ion-col (click)="openPage('RefilHistoryPage');">
<div><img src="assets/icon/icon-quickpay.png">{{"refil_history" | translate}}</div>
</ion-col>
</ion-row>
<ion-row>
<ion-col (click)="openPage('ServicesPage');">
<div><img src="assets/icon/icon-mechanic.png">{{"service_request" | translate}}</div>
</ion-col>
<ion-col>
<button [disabled]="!clickhandle" (click)="emergencyCall();"><img src="assets/icon/icon-emergency.png">{{"emergency_helpline" | translate}}</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Side Menu Page language.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { NgForm,FormBuilder, FormGroup, Validators } from '#angular/forms';
import { TranslateService } from '#ngx-translate/core';
import { Storage } from '#ionic/storage';
#IonicPage()
#Component({
selector: 'page-language',
templateUrl: 'language.html',
})
export class LanguagePage {
public langform:FormGroup;
public langcod:string;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public formBuilder: FormBuilder,
public translate: TranslateService,
public storage: Storage) {
this.storage.get('AppLangcode')
.then((AppLangcode) => {
if(AppLangcode==null){
this.langcod = 'en';
this.langform.get('langcode').setValue(this.langcod);
}else{
this.langcod = AppLangcode;
this.langform.get('langcode').setValue(this.langcod);
}
})
this.langform = formBuilder.group({
langcode: [this.langcod, Validators.required]
});
}
langselect(form: NgForm){
let langselcode = this.langform.value.langcode;
this.storage.set('AppLangcode', langselcode);
this.translate.setDefaultLang(langselcode);
this.translate.use(langselcode);
}
}
language.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
declarations: [
LanguagePage,
],
imports: [
IonicPageModule.forChild(LanguagePage),
TranslateModule.forChild()
],
exports: [
LanguagePage
]
})
export class LanguagePageModule {}
language.html
<ion-header>
<ion-navbar color='navbarColor'>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="langform" (submit)="langselect($event)">
<ion-list radio-group formControlName="langcode">
<ion-row responsive-sm>
<ion-col col-6>
<ion-item>
<ion-label>{{"english" | translate}}</ion-label>
<ion-radio value="en" checked></ion-radio>
</ion-item>
<ion-item>
<ion-label>{{"hindi" | translate}}</ion-label>
<ion-radio value="hi"></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</ion-list>
<ion-row responsive-sm>
<ion-col>
<button ion-button block type="submit" [disabled]="!langform.valid">
Submit
</button>
</ion-col>
</ion-row>
</form>
</ion-content>
en.json
{
"english" : "English",
"hindi" : "हिंदी",
"quick_book_pay":"Quick Book & Pay",
"refil_history":"Refill History",
"service_request":"Service Request",
"emergency_helpline":"Emergency Helpline"
}
hi.json
{
"english" : "English",
"hindi" : "हिंदी",
"quick_book_pay":"त्वरित बुक और भुगतान करें",
"refil_history":"रीफिल इतिहास",
"service_request":"सेवा अनुरोध",
"emergency_helpline":"आपातकालीन हेल्पलाइन"
}
On change language it show keys instead translation. Please let me know what wrong i am doing ?

i have updated my language module and this worked for me, not sure if this is right way but it's worked.
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpModule,Http } from '#angular/http';
export function createTranslateLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
declarations: [
LanguagePage,
],
imports: [
IonicPageModule.forChild(LanguagePage),
TranslateModule.forChild({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
})
],
exports: [
LanguagePage
]
})
export class LanguagePageModule {}
i have added loader for child and export TranslateHttpLoader in language.module.ts
language.ts
langselect(form: NgForm){
let langselcode = this.langform.value.langcode;
this.storage.set('AppLangcode', langselcode);
this.translate.use(langselcode);
}

I spent hours to get it working on Ionic 3. Finally I had to add HttpClientModule to the import section of app.module.ts. Hope that helps.
[2]: Use HttpClient instead of Http
[3]: Add HttpClientModule
[4]: Use HttpClient instead of Http
src/app/app.module.ts:
import {HttpClient, HttpClientModule} from "#angular/common/http";
import {HttpModule, RequestOptions, XHRBackend} from '#angular/http';
import {TranslateModule, TranslateLoader} from '#ngx-translate/core';
import {TranslateHttpLoader} from '#ngx-translate/http-loader';
export function createTranslateLoader(http: HttpClient [2]) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
...
imports: [
BrowserModule,
HttpModule,
HttpClientModule [2],
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient] [3]
}
...
...
}),
src/pages/[your-page]/[your-page].module.ts
imports: [
IonicPageModule.forChild(LoginPage),
TranslateModule.forChild(),
],

I had the same issue and managed to fix it. I'm lazy loading the pages and the problem occurred when I try to change the language from a component. He's how I fixed it.
app.component.ts
this.translateService.addLangs(['en', 'lk']);
this.translateService.setDefaultLang("en");
this.eventProvider.currentLang.subscribe(lang => {
this.translateService.use(lang);
});
event-provider.ts
import { EventEmitter } from '#angular/core';
export class EventProvider {
public currentLang: EventEmitter<string> = new EventEmitter();
setLang(val) {
this.currentLang.emit(val);
}
}
Import event-provider.ts to App Module and include in providers.
Now you can import it to any component where you need to change the language and emmit the value.
custom-header-component.ts
setLanguage(val:string) {
this.eventProvider.setLang(val);
}

Finally, i a solve this issue by using HttpClientModule in the import section of app.module.ts. maybe it helps.
First: Import HttpClientModule
Second: Use HttpClient instead of Http.
So, the code is as follow: app.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
//translate related imports
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '#angular/common/http';
#NgModule({
declarations: [
HomePage,
],
imports: [
IonicPageModule.forChild(HomePage),
HttpClientModule
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient ]
}
})
],
exports: [
HomePage
]
})
export class HomePageModule {}
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
In app.component.ts add this line in constructor.
import {TranslateService} from '#ngx-translate/core';
...
translate.setDefaultLang('en');//So English language set
And then you have to create two JSON files in ./assets/i18n/ path.
en.JSON
{
"title": "Translation demo",
"text": "This is a simple demonstration app for {{value}}"
}
Then use in your app with PIPE filter like this.
<h1>{{'title' | translate}}</h1>
OR
<h1 [translate]="'title'"></h1>
We can also pass a parameter.
<h1>{{'text' | translate:{'value':'ngx-translate'} }}</h1>
OR
<h1 [translate]="'text'" [translateParams]="{value: 'ngx-translate'}"></h1>

Related

I can't connect my ionic app with a mysql database

In a project that I have to do I was copying some lines from a youtube project, trying to connect the login page to a mysql database. All the project is in a htdocs folder of xampp, also there is a server_api folder with a config.php (I describe its content below) and a file_aski.php (with nothing in it). Please any help would be great! Thanks.
The files that I describe below are:
config.php
app.module.ts
app.component.ts
app-routing.module.ts
login.page.ts
login.page.html
---------- config.php ----------
<?php
// setting config database
define('DB_NAME', 'dbtotalinspector');
define('DB_USER', 'root');
define('DB_PASSWORD', ''); // default
define('DB_HOST', 'localhost'); // default xampp
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>
---------- 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 { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
/* import { HttpModule } from '#angular/http';
import { PostProvider } from '../providers/post-provider';
import { IonicStorageModule } from '#ionic/storage-angular';
*/
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule /* , IonicStorageModule.forRoot(), PostProvider*/],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy } /*, PostProvider */ ],
bootstrap: [AppComponent],
})
export class AppModule {}
---------- app.component.ts ----------
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
constructor() {}
}
---------- app-routing.module.ts ----------
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
},
{
path: 'seleccionar-obra',
loadChildren: () => import('./seleccionar-obra/seleccionar-obra.module').then( m => m.SeleccionarObraPageModule)
},
{
path: 'cargar-obra',
loadChildren: () => import('./cargar-obra/cargar-obra.module').then( m => m.CargarObraPageModule)
},
{
path: 'cargar-item',
loadChildren: () => import('./cargar-item/cargar-item.module').then( m => m.CargarItemPageModule)
},
{
path: 'desplegar-items-de-obra',
loadChildren: () => import('./desplegar-items-de-obra/desplegar-items-de-obra.module').then( m => m.DesplegarItemsDeObraPageModule)
},
{
path: 'tomar-fotografia',
loadChildren: () => import('./tomar-fotografia/tomar-fotografia.module').then( m => m.TomarFotografiaPageModule)
},
{
path: 'generar-informe',
loadChildren: () => import('./generar-informe/generar-informe.module').then( m => m.GenerarInformePageModule)
},
{
path: 'confirmar-enviar-informe',
loadChildren: () => import('./confirmar-enviar-informe/confirmar-enviar-informe.module').then( m => m.ConfirmarEnviarInformePageModule)
},
{
path: 'desplegar-foto',
loadChildren: () => import('./desplegar-foto/desplegar-foto.module').then( m => m.DesplegarFotoPageModule)
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
---------- login.page.ts ----------
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
btnClickIngresar(){
this.router.navigateByUrl('/home');
}
}
---------- login.page.html ----------
<app-header></app-header>
<ion-content>
<div class="container">
<ion-card>
<ion-card-header>
<ion-card-title>Iniciar sesión</ion-card-title>
</ion-card-header>
<ion-card-content>
<ion-item>
<ion-icon name="person-outline" slot="start"></ion-icon>
<ion-item>
<ion-label position="floating">Usuario</ion-label>
<ion-input></ion-input>
</ion-item>
</ion-item>
<ion-item>
<ion-icon name="lock-open-outline" slot="start"></ion-icon>
<ion-item>
<ion-label position="floating">Contraseña</ion-label>
<ion-input type="password"></ion-input>
</ion-item>
</ion-item>
<ion-button expand="full" (click)="btnClickIngresar();">INGRESAR</ion-button>
</ion-card-content>
</ion-card>
</div>
</ion-content>
Thanks for all the advices, I'm reading the guidelines. Ok, I see that I have to cut the code to the most importan parts. As I see, the main problem is in "post-providers.ts" and maybe in in "app.module.ts" too. I took out the code between /* */ I will show you how the code looks and the error messages.
post-providers.ts
// providers api
import { Injectable } from "#angular/core";
import { Http,Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PostProvider {
server: string = "http://localhost/server_api";
constructor (public http: Http){
}
postData(body, file){
let type = "application/json; charset=UTF-8";
let headers = new Headers({ 'Content-Type': type });
let options = new RequestOptions ({ headers: headers });
return this.http.post(this.server + file, JSON.stringify(body), options)
.map(res => res.json());
}
}
NOTE: on ".map" of the code above it says "Property 'map' does not exist on type 'Observable'.ts(2339)"
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 { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpModule } from '#angular/http';
import { PostProvider } from '../providers/post-provider';
import { IonicStorageModule } from '#ionic/storage-angular';
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, IonicStorageModule.forRoot(), PostProvider, HttpModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, PostProvider ],
bootstrap: [AppComponent],
})
export class AppModule {}
NOTE: in app.module.ts, the "HttpModule" is cross out (or strike out) in both, "import {}" and the imports inside #NgModule of
The site appears in blank and it is compiled succesfully. But I don't see the login page.
THE ERRORS ARE:
./node_modules/rxjs/add/operator/map.js:7:0-39 - Error: Module not found: Error: Can't resolve 'rxjs-compat/add/operator/map' in 'C:\xampp\htdocs\totalinspector\node_modules\rxjs\add\operator'
[ng]
[ng] Error: src/providers/post-provider.ts:21:10 - error TS2339: Property 'map' does not exist on type 'Observable<Response>'.
[ng]
[ng] 21 .map(res => res.json());
[ng] ~~~
[ng] × Failed to compile.

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

get data from local Json file ionic 3 [duplicate]

This question already has answers here:
No provider for HttpClient
(25 answers)
Closed 5 years ago.
I start a dummy project in Ionic. I try to get data from a local Json file but I have this error :
I don't understand why there is no provider for HttpClient.
For further details, I actually tried to follow this tutorial : https://www.youtube.com/watch?v=vuc4dp0qHSc
How can I fix this error and get the data ?
Versions
Ionic 3.18.0
Angular 5.0.1
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { FirstPage } from '../pages/first/first';
import { CardsDataProvider } from '../providers/cards-data/cards-data';
#NgModule({
declarations: [
MyApp,
HomePage,
FirstPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
FirstPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
CardsDataProvider,
]
})
export class AppModule {}
cards-data.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the CardsDataProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class CardsDataProvider {
constructor(public http: HttpClient) {
console.log('Hello CardsDataProvider Provider');
}
getLocalData() {
this.http.get('../assets/data/cards.json').map(res => res.json()).subscribe(data =>
{
console.log(data);
});
}
}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FirstPage } from '../first/first';
import { CardsDataProvider } from '../../providers/cards-data/cards-data';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public CardsService: CardsDataProvider) {
}
openFirstPage() {
this.navCtrl.push(FirstPage);
}
ionViewDidLoad() {
this.CardsService.getLocalData();
}
}
Any help will be appreciated.
You are following an Ionic2 tutorial while using Ionic3 with Angular5.
For Http to work since Ionic 3.0, you need to include HttpClientModule in your imports in app.module.ts.
import {HttpClientModule} from '#angular/common/http';//import
#NgModule({
declarations: [
MyApp,
HomePage,
FirstPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpClientModule//include here
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
FirstPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
CardsDataProvider,
]
})
export class AppModule {}
Also, in your cards-data.ts,
import {Http} from '#angular/common/http';
#Injectable()
export class CardsDataProvider {
constructor(public http: HttpClient) { //change here
console.log('Hello CardsDataProvider Provider');
}
For further changes to go from Ionic 2 to 3 check here. For changes required to go to Angular 5 check here.
A simpler way is to find a more recent tutorial.

Navigating & Passing Data Between Pages Ionic 2

I'm having some issues while navigating between pages with Ionic2.
I have a List of Data, that I got from a data.json
Here is the list
I want to get details:
Example - From "A"
The data that I have on my data/Example.Json
{
"title": "A",
"lat": 2.323733,
"lon": 64,546465
},
So as soon as I click on the Title, I want to get the title, lat and lon on a new page.
app.modules.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;
#NgModule({
declarations: [
MyApp,
HomePage,
MapPage,
ListPage,
DetailPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
MapPage,
ListPage,
DetailPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { MapPage } from '../pages/map/map';
import { ListPage } from '../pages/list/list';
import { DetailPage } from '../pages/detail/detail';
import { Locations } from '../providers/locations';
import { GoogleMaps } from '../providers/google-maps';
import { Connectivity } from '../providers/connectivity';
declare var google: any;
#NgModule({
declarations: [
MyApp,
HomePage,
MapPage,
ListPage,
DetailPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
MapPage,
ListPage,
DetailPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Locations,GoogleMaps, Connectivity]
})
export class AppModule {}
PageA.ts ( list of Data )
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Locations } from '../../providers/locations';
import { DetailPage } from '../detail/detail';
#Component({
selector: 'page-list',
templateUrl: 'list.html'
})
export class ListPage {
constructor(public navCtrl: NavController, public locations: Locations) {
}
ionViewDidLoad() {
console.log('Test Si marche');
}
viewLocation(event,location) {
this.navCtrl.push(DetailPage, {
"title":location.title,
"longitude":location.longitude
})
}
}
Page B ( where i want to get the detail as soon as i click on something on the list )
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {NavParams} from "ionic-angular";
import { Locations} from '../../providers/locations';
import { ListPage } from '../list/list';
#Component({
selector: 'page-detail',
templateUrl: 'detail.html',
providers: [ Locations ],
entryComponents:[ ListPage ]
})
export class DetailPage {
title: string
latitude: string
navParams: NavParams
constructor(navParams: NavParams,public navCtrl: NavController) {
this.navParams = navParams
this.title = this.navParams.get('title');
this.latitude = this.navParams.get('latitude');
}
ionViewDidLoad(err) {
console.log(err);
}
goBack() {
this.navCtrl.pop();
}
}
listA.html
<ion-header>
<ion-navbar color="secondary">
<ion-title>List</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list no-lines>
<ion-item *ngFor="let location of locations.data">
<ion-item (click)="viewLocation($event, locations)">{{locations.title}}</ion-item>
<ion-avatar item-left>
<ion-icon name="pin"></ion-icon>
</ion-avatar>
<!--<img src="./src/pics/mus.png"/>-->
<h2>{{location.title}}</h2>
<p>{{location.distance*1.609}} Km</p>
</ion-item>
</ion-list>
</ion-content>
data.json
[
{ "title": "Cat", "longitude": "14,57" },
{ "title": "Bird", "longitude": "17.45" },
{ "title": "Spider", "longitude": "19,12" }
]
If you want to pass data from one page to another, you can either
1) Store your JSON data in SQL format via JSON.stringify(store) and JSON.parse(retrieving) method.
Meaning you stringify the data, before storing inside the SQL table and once retrieved from the next page, you do a JSON.parse to get back your JSON object.
You may want to read up on the following article on how to store data in SQL.
SQL Ionic 2
JSON Parse
JSON Stringify
Or either which, 2) you can make use of navController to "push" data from one page to another. One downside would be if your JSON data is huge, you will have to slowly iterate through.
A simple example would be:
this.navController.push(ThePageNameYouWannaGo, {
firstPassed: "firstData",
secondPassed: "secondData",
thirdPassed: "thirdData",
});
//On the next page (at your constructor),
Constructor(....,NavParams,.....){
this.first = navParams.get("firstPassed");
this.second= navParams.get("secondPassed");
this.third= navParams.get("thirdPassed");
//the value would be stored inside this.first, this.second respectively
For your case, I would recommend method 1 as I have no clue how big is your JSON file and to make your life easier in the future when your JSON file changes.