This code has been bugging me for a good four hours... It's supposed to sign up a user with Firebase's auth system and Ionic 4 components.
Instead it returns the following around a good six times:
ERROR TypeError: Cannot read property 'email' of undefined
Another weird thing is that my code will only nitpick on the property 'email', and won't return errors for having a property 'password'.
signup.page.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
// firebase imports
import * as firebase from 'firebase';
import { AngularFireAuth } from '#angular/fire/auth';
import { ToastController } from '#ionic/angular';
// model import
import { User } from '../../models/login.interface';
#Component({
selector: 'app-signup',
templateUrl: './signup.page.html',
styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {
constructor(
private afAuth: AngularFireAuth,
private route: Router,
public toast: ToastController
) { }
ngOnInit() {
}
async signup(user: User) {
console.log('starting auth');
try {
const result = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
if (result) {
this.route.navigateByUrl('/add-profile');
}
} catch (e) {
console.log(e);
}
}
}
signup.page.html
<ion-header>
<ion-toolbar>
<ion-title>SIGNUP</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label position="stacked">Email</ion-label>
<ion-input type="text" [(ngModel)]="user.email"></ion-input>
</ion-item>
<ion-item>
<ion-label position="stacked">Password (6+ characters)</ion-label>
<ion-input type="password" [(ngModel)]="user.password"></ion-input>
</ion-item>
<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button (click)="signup(user)">SIGNUP
</ion-fab-button>
</ion-fab>
</ion-content>
user.interface.ts
export interface User {
email: string;
pasword: string;
}
Any help would be appreciated! Thank you!
Create a user and initialize it with empty values either in constructor or ngOnInit like below
user:User;
//inside constructor or ngOnInit
this.user = {
email: '',
pasword: ''
}
// firebase imports
import * as firebase from 'firebase';
import { AngularFireAuth } from '#angular/fire/auth';
import { ToastController } from '#ionic/angular';
// model import
import { User } from '../../models/login.interface';
#Component({
selector: 'app-signup',
templateUrl: './signup.page.html',
styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {
user: User = {
email: '',
password: ''
}
constructor(
private afAuth: AngularFireAuth,
private route: Router,
public toast: ToastController
) { }
ngOnInit() {
}
async signup(user: User) {
console.log('starting auth');
try {
const result = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
if (result) {
this.route.navigateByUrl('/add-profile');
}
} catch (e) {
console.log(e);
}
}
}
Related
I am performing the login using API in Ionic but I am getting the error :
Error: Property 'json' does not exist on type '{}'.
This is my loginpage.html:
<ion-header>
<ion-navbar>
<ion-title>loginpage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form (submit)="getloginUsers()">
<ion-list>
<ion-item>
<ion-label fixed>Email</ion-label>
<ion-input type="email" [(ngModel)]="userData.email" name="email"></ion-input>
</ion-item>
<ion-item>
<ion-label fixed>Password</ion-label>
<ion-input type="password" [(ngModel)]="userData.password" name="password"></ion-input>
</ion-item>
<div padding>
<button ion-button color="primary" block>Login</button>
</div>
</ion-list>
</form>
</ion-content>
This is my loginpage.ts:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RestapiProvider } from '../../providers/restapi/restapi';
import { ListPage } from '../list/list';
#IonicPage()
#Component({
selector: 'page-loginpage',
templateUrl: 'loginpage.html',
})
export class LoginpagePage {
responseData : any;
userData = {"email": "", "password": ""};
constructor(public navCtrl: NavController, public navParams: NavParams,
public restProvider: RestapiProvider) {
this.getloginUsers();
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginpagePage');
}
getloginUsers(){
this.restProvider.getUsers(this.userData,'user_Login').then((result) => {
if(result){
this.responseData = result.json();
if(this.responseData.userData){
console.log(this.responseData);
console.log("User Details");
this.navCtrl.push(ListPage);
}
else{
console.log("Incorrect Details"); }
}
}
, (err) => {
// Error log
});
}
}
This is code this.responseData = result.json(); error is coming.
Error: Property 'json' does not exist on type '{}'.
This is my Service restapi.ts:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { HttpHeaders } from '#angular/common/http';
import { Response } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout'
let apiUrl = 'http://192.168.1.10/honeybee/HoneyApi/';
#Injectable()
export class RestapiProvider {
token:any;
constructor(public http: HttpClient) {
console.log('Hello RestapiProvider Provider');
}
getUsers(credentials, type) {
return new Promise((resolve, reject) => {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.subscribe((res: Response) => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
}
I have included the FormsModule in app.module.ts. Any help is much appreciated.
Since you are using HttpClient, you dont have to generally use result.json();
this.responseData = result;
Also you do not have to use Promise, change the service code as follows,
getUsers(credentials, type) {
var headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
return this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers});
}
and in your component,
this.restProvider.getUsers(this.userData,'user_Login').subscribe((data) => {
console.log(data);
});
I created a login page which data I want to store to localStorage when passed from php api, but whenever i click on the button to the login page an error always occured.
i have searched through the net for a more details based on this error but I was unable to come up with anything.
Below is the error displayed to my screen when I tried to access my login page:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[MyloginPage -> AuthServiceProvider]:
StaticInjectorError(Platform: core)[MyloginPage -> AuthServiceProvider]:
NullInjectorError: No provider for AuthServiceProvider!
Error: StaticInjectorError(AppModule)[MyloginPage -> AuthServiceProvider]:
Below is the image:
Mylogin.html
<ion-content padding>
<ion-list>
<ion-item>
<ion-label>username</ion-label>
<ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
</ion-item>
<ion-item>
<ion-label>password</ion-label>
<ion-input type="password" name="password" [(ngModel)]="data.password"></ion-input>
</ion-item>
</ion-list>
<button ion-button color="primary" full (click)="login()">Login</button>
</ion-content>
**mylogin.ts**
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
import { Storage } from '#ionic/storage';
/**
* Generated class for the MyloginPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-mylogin',
templateUrl: 'mylogin.html',
})
export class MyloginPage {
data: any;
public local : Storage;
constructor(public navCtrl: NavController, public navParams: NavParams, private viewCtrl: ViewController, private service: AuthServiceProvider) {
this.data = {};
this.data.username = "";
this.data.password = "";
this.local = new Storage(null);
}
ionViewDidLoad() {
console.log('ionViewDidLoad MyloginPage');
}
login() {
let username = this.data.username;
let password = this.data.password;
let data = JSON.stringify({username, password});
this.service.postLogin(data);
}
dismiss(){
this.viewCtrl.dismiss();
}
}
Auth-service.ts
//import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '#ionic/storage';
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AuthServiceProvider {
public local : Storage;
mydata: any;
constructor( public http: Http) {
this.local = new Storage(null)
}
postLogin(data){
let link = "http://textkhmer.com/api/securelogin.php";
return this.http.post(link, data)
.map(data => {
this.mydata = data;
console.log("data")
}, error =>{
console.log(error)
})
}
}
Please why is this error displaying?
Thanks
Hi Developpers i am working in projet where i need to load data from database and show it in the page in ionic , i didn't found any problem but it didn't work too
here is the page of getting data from database
<?php
include("db.php");
header("Access-Control-Allow-Origin: *");
$query = "select * from etudiant";
$result = $db->query($query);
$res['etudiant'] = [];
while ($etud = $result->fetch_assoc()) {
$res['etudiant'][] = $etud;
}
echo json_encode($res);
and this is the component page
import {Component} from '#angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {EtudiantProvider} from "../../providers/etudiant/etudiant";
#IonicPage()
#Component({
selector: 'page-etudiant',
templateUrl: 'etudiant.html',
})
export class EtudiantPage {
public isSearchbarOpened = false;
etudiant:String;
constructor(public navCtrl: NavController, NavParams: NavParams, public etudiantProvider: EtudiantProvider) {
}
ngOnInt() {
this.etudiantProvider.getEtudiant().subscribe(
data => (
this.etudiant=data.etudiant.nom
),
error => {
console.log(error);
}
)
}
}
and here is my providers
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class EtudiantProvider {
url: string;
constructor(public http: Http) {
console.log('Hello Provider');
this.url = "http://localhost/eportfolio/api.php";
}
getEtudiant(){
return this.http.get(this.url+"?action=getEtudiant").map(res => res.json())
}
}
and this is the page where i need to show data
<ion-list [virtualScroll]="etudiant" [approxItemHeight]="'250px'">
<ion-item *virtualItem="let etud">
<ion-avatar item-start id="avatar">
<p id="letters">AF</p>
</ion-avatar>
<h1>{{etud.nom}}</h1>
<button ion-item clear no-lines>{{etud.nom}}</button>
<button ion-item clear no-lines>{{etud.prenom}}</button>
</ion-item>
</ion-list>
export class etudiantEntity{
constructor(public nom: string, public prenom: string){}
}
create a class like that
and modify your Etudiant
export class EtudiantPage {
public isSearchbarOpened = false;
etudiant:etudiantEntity;
...etc
This might solve your problem
Somebody please help me. I am trying to filter a JSON data but it does not working and also don't show an error.
i have read the ionic Documentation, but it just work for an array data.
this is my ts file
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
//untuk membaca file json
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//navigasi ke tampilPage
import { TampilPage } from '../tampil/tampil';
//panggil provider
import { AlQuranProvider } from '../../providers/al-quran/al-quran';
#Component({
selector: 'page-al-quran',
templateUrl: 'al-quran.html',
})
export class AlQuranPage {
searchQuery: string = '';
public alquranTerfilter: string[];
constructor(
private quranProvider: AlQuranProvider,
private http: Http,
public navCtrl: NavController,
public navParams: NavParams) {
}
ionViewDidLoad(){
this.quranInitializeItems();
}
quranInitializeItems(){
this.quranProvider.getQuran().subscribe(
(respon) => {
//this.alquran = respon;
this.alquranTerfilter = respon;
});
}
getItems(ev: any) {
// Reset items back to all of the items
this.quranInitializeItems();
// set val to the value of the searchbar
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
}
tampilkan(item){
this.navCtrl.push(TampilPage, {item: item});
}
}
//this.alquran = respon;
/*
if (val && val.trim() != '') {
this.alquranTerfilter = this.alquranTerfilter.filter((item) => {
return (item.toString().toLowerCase().indexOf(val.toString().toLowerCase()) > -1);
})
}
*/
<!--
Generated template for the AlQuranPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>AlQuran</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of alquranTerfilter" (click)="tampilkan(item)">
<h2>{{item.judul}}</h2>
<h4>{{item.riwayat}}</h4>
<ion-icon name="arrow-forward" item-end></ion-icon>
</ion-item>
</ion-list>
</ion-content>
and this the provider
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the AlQuranProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class AlQuranProvider {
// public alquran: string[];
//public alquranTerfilter: string[];
constructor(public http: HttpClient, private httpnonclient: Http) {
}
getQuran(){
return this.httpnonclient.get('./assets/nash/tbQuran.json')
.map(respon => respon.json());
}
}
the filter doesn't working and doesn't showing any error.
sorry for my bad english.
I guess it's a search function right ? Try this
getItems(ev: any) {
this.quranInitializeItems();
var val = ev.target.value;
if (val && val.trim()) {
this.alquranTerfilter = this.alquranTerfilter.filter(
item => item.toString().toLowerCase().includes(val.toString().toLowerCase())
)
} else {
return [];
}
}
I didn't get your filter logic, and you forgot to return something in case your query is empty.
Is there any way to send data {{error.value}} to another page using a method?
This is my code
<ion-row *ngFor="let errors of adp_principal_menuRS">
<ion-col class="info-col" col-4>
<button ion-button color="primary" small (click)="goToErrors(errors.event)">
{{errors.event}}
</button>
</ion-col>
</ion-row>
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
});
}
I want to send the {{errors.event}} value to another page in the goToErrors() method.
Thanks!
EDIT: I just achieve what I want. I edited the code
Data can be shared using BehaviorSubject between components via service.
Here is an example:
// service.ts
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ShareService {
private errorSource = new BehaviorSubject<any>(null);
error$ = this.errorSource.asObservable();
setError(error: any){
this.errorSource.next(error);
}
Set the error event in parent component using setError method and subscribe the error in error component.
// error component.ts
constructor(share: ShareService) {
share.error$.subscribe(Err => this.error = Err);
Why don't you send the value using a navParam?
goToErrors(menu: string){
console.log(menu);
this.navCtrl.push(AdpDetailPage, {
errorEvent: menu // <------------------------- Add this line
});
}
And in your AdpDetailPage:
export class AdpDetailPage{
constructor(public navParams: NavParams){
errorEvent = this.navParams.get('errorEvent');
console.log("errorEvent= ", errorEvent);
}
}
Use event emittor.
//Home component.ts import { Events } from 'ionic-angular'; constructor(public events: Events) {} directioChange(user) {this.events.publish('directiochanged', 'true');} //App.component.ts constructor(public events: Events) { events.subscribe('directiochanged', (direction) => { this.isRtl = direction;console.log(direction);});}
I generated a Plunker that hopefully matches with what you are trying to do.
https://plnkr.co/edit/MNqpIqJjp5FN30bJd0RB?p=preview
Service
import { Injectable } from '#angular/core';
#Injectable()
export class ErrorService {
errorInfo: string;
}
Component
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<button (click)="goToErrors()">{{errors.event}} </button>
<router-outlet></router-outlet>
</div>
`,
})
export class App {
name:string;
errors = { event: 'Test Error', otherInfo: 'Test Info' };
constructor(private errorService: ErrorService, private router: Router) {
this.name = `Angular! v${VERSION.full}`
}
goToErrors(): void {
// Code to navigate to the other component
this.errorService.errorInfo = this.errors.event;
this.router.navigate(['/a']);
}
}