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

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.

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 }}

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']

Module has no exported member 'http' [2305]

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.

Angular 6 component not showing up

I just started learning Angular yesterday so I apologize if I'm missing something obvious, but I am trying to display a component on the app.component.html, however, it is not showing up.
TS file for the component I am trying to display:
import { Component, OnInit } from '#angular/core';
import { ImageService } from '../shared/image.service';
#Component({
selector: 'image-list',
templateUrl: './image-list.component.html',
styleUrls: ['./image-list.component.css']
})
export class ImageListComponent implements OnInit {
images: any[];
constructor(private _imageService : ImageService ) { }
searchImages(query : string)
{
return this._imageService.getImage(query).subscribe
(
data => console.log(data),
error => console.log(error),
() => console.log("Request Completed!")
);
}
ngOnInit() {
}
}
image-list.component.html :
<button>Find Images</button>
app.component.html :
<image-list></image-list>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
image.service.ts
import { Injectable } from "#angular/core";
import { environment } from "../../environments/environment";
import { Http, Headers } from "#angular/http";
import { map, filter, scan } from 'rxjs/operators';
#Injectable()
export class ImageService
{
private query: string;
private API_KEY: string = environment.API_KEY;
private API_URL: string = environment.API_URL;
private URL: string = this.API_URL + this.API_KEY + '&q=';
constructor(private _http: Http) {
}
getImage(query)
{
return this._http.get(this.URL + this.query).pipe(
map((res) => res.json));
}
}
I had a similar problem trying to use a component outside its module.
In this case, you have to export a component from your .module.ts:
#NgModule({
// …
declarations: [ MyComponent ],
exports: [ MyComponent ],
// …
})
You need to import your Component and your Service into your app.module.ts and then to declarations and to providers property
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list.component';
import { ImageService } from './image.service';
#NgModule({
declarations: [
AppComponent,
ImageListComponent
],
imports: [
BrowserModule
],
providers: [ ImageService ],
bootstrap: [AppComponent]
})
export class AppModule { }
Adjust ImageListComponent path into the import statement.
Teorically when you generate a component with Angular CLI with a command like this:
ng generate component image-list
it should update your app.module.ts file for you.
To generate a service use
ng generate service image
check this one
in src/app/app.module.ts
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
bootstrap: [AppComponent],
})
export class AppModule {}
from this link: https://malcoded.com/posts/why-angular-not-works/
You may try the Angular tutorial from: https://angular.io/start . It shows how to render a custom Ansible component on the app.component.html page.
You just need to update the app.module.ts file. Assuming your component is named ImageListComponent:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router'; // add this line
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list/image-list.component'; // add this line
#NgModule({
declarations: [
AppComponent,
ImageListComponent // add this line
],
imports: [
BrowserModule,
// add the following 3 lines
RouterModule.forRoot([
{ path: '', component: ImageListComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
First try this, without adding any custom services.
It seems you have nothing that triggers the API call on your method searchImages in ImageComponent. Having a click eventListener on the <button>Find Images</button> tag should do the trick. Also register the ImageComponent and ImageService in your app.module.ts file.

ngx-translation issue with ionic 3 app

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>