I am working on auto-verification otp ionic2. In that, SMS permission is applied and if device mobile number exists or read otp from sms then it switch directly to dashboard page for that i use a function called watchSMS() as shown in angular code but it gives an error (SMS is not defined).
Any help will be highly appreciated.
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, AlertController, Platform, LoadingController, ToastController, ViewController } from 'ionic-angular';
import { FormGroup, FormBuilder, FormControl, Validators } from '#angular/forms';
import { Network } from '#ionic-native/network';
import { CrudHttpProvider } from '../../providers/crud-http/crud-http';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { ConstantVariable } from '../../app/constant-variable';
import { HomePage } from '../home/home';
// import { SMS } from '#ionic-native/sms';
import { Sim } from "#ionic-native/sim";
import { AndroidPermissions } from '#ionic-native/android-permissions';
declare var window: any;
declare var SMS:any;
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
public myForm: FormGroup;
public mobile: any;
public db_name: any;
public url_play_store: any;
public buttonDisabled: any;
public studname: any;
public tuition_name: any;
public prn: any;
public otp: any;
public api_key: any;
public userinfo:any;
public stored_mb:any;
public simInfo: any;
public cards: any;
public phoneNumber: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, public alertCtrl: AlertController, public platform: Platform, public network: Network, public loadingCtrl: LoadingController, public toastCtrl: ToastController, public crudHttpProvider: CrudHttpProvider, public sqlite: SQLite, public viewCtrl: ViewController, public sim: Sim, public androidPermissions: AndroidPermissions) {
this.db_name = ConstantVariable.db_name;
this.myForm = this.formBuilder.group({
'mobile': ['', [Validators.required]],
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
login() {
let post_data = { 'api_url': 'checkMobileNumber', "post": {'mobile': this.mobile} };
this.crudHttpProvider.callToCrudPost(post_data)
.then(data => {
let res = data;
if (res['status'] == 100) {
this.studname = res['data'].studname;
this.tuition_name = res['data'].tuition_name;
this.prn = res['data'].prn;
this.otp = res['data'].otp;
this.api_key = res['data'].api_key;
this.navCtrl.push('RegisterPage',{
"studname": this.studname,
"tuition_name": this.tuition_name,
"prn": this.prn,
"otp": this.otp,
"api_key": this.api_key
});
this.viewCtrl.dismiss();
this.checkPermission();
}
});
}
checkPermission() {
this.androidPermissions.checkPermission
(this.androidPermissions.PERMISSION.READ_SMS).then(
success => {
//if permission granted
this.watchSMS();
},
err =>{
this.androidPermissions.requestPermission
(this.androidPermissions.PERMISSION.READ_SMS).
then(success=>{
this.watchSMS();
},
err=>{
alert("cancelled")
});
});
this.androidPermissions.requestPermissions
([this.androidPermissions.PERMISSION.READ_SMS]);
}
watchSMS() {
if(window.SMS) window.SMS.startWatch(function(){
console.log('Succeed to start watching SMS');
this.navCtrl.push('DashboardPage');
let toast = this.toastCtrl.create({
message: "Succeed to start watching SMS.",
duration: 4000
});
toast.present();
document.addEventListener('onSMSArrive', this.smsArived);
}, function(){
console.log('failed to start watching SMS');
let toast = this.toastCtrl.create({
message: "failed to start watching SMS.",
duration: 4000
});
toast.present();
});
}
stopWatchSMS() {
if(window.SMS) window.SMS.stopWatch(function(){
console.log('Succeed to stop watching SMS');
}, function(){
console.log('failed to stop watching SMS');
});
}
smsArived = (result: any) => {
console.log("SMS DATA 2" + result);
let toast = this.toastCtrl.create({
message: "RESULT " + result,
duration: 4000
});
toast.present();
this.stopWatchSMS();
}
}
I implemented auto verify OTP via this tutorial. I had no trouble.
SMS is called inside of platform.ready() and it says : "Make sure always use method in Ionic Framework inside the platform.ready() else it will not work.". Finally, I think, you dont need to use window.
ionViewDidEnter()
{
this.platform.ready().then((readySource) => {
if(SMS) SMS.startWatch(()=>{
console.log('watching started');
}, Error=>{
console.log('failed to start watching');
});
document.addEventListener('onSMSArrive', (e:any)=>{
var sms = e.data;
console.log(sms);
});
});
}
Related
I'm trying to make many request in nestJs and specially some with the role of my users and i wanted to be able to list all users who match user.role = "Role's name" but i can't get the foreign key user from my table role.
My controller look like this and both of my entities reference each other as a role can have one or many user and a user one and only one role.
import { Controller, Get, Param, Post } from '#nestjs/common';
import { Body } from '#nestjs/common/decorators';
import { AuthDto } from 'src/authentification/auth.dto';
import { Role } from './role.entity';
import { User } from './user.entity';
import { UserService } from './user.service';
#Controller('user')
export class UserController {
constructor(private readonly UserService: UserService){}
#Get()
async getAllUser(): Promise<User[]>{
return this.UserService.getListUser();
}
#Get('/Role')
async getListRole(): Promise<Role[]> {
return this.UserService.getListRole();
}
#Get('/Role/:role')
async getUserByRole(#Param('role') role : number): Promise<User[]> {
return this.UserService.getUserByRole(+role);
}
#Get('/Pseudo/:pseudo')
async getUserByPseudo(#Param('pseudo') pseudo : string): Promise<User> {
return this.UserService.getUserByPseudo(pseudo);
}
#Get('/id/:id')
async getUserById(#Param('id') id : number): Promise<User> {
return this.UserService.getUserById(+id);
}
#Post('/New')
async createUser(#Body() user: AuthDto){
return this.UserService.createUser(user);
}
}
and here is the service
import { Get, Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { AuthDto } from 'src/authentification/auth.dto';
import { Repository } from 'typeorm';
import { Role } from './role.entity';
import { User } from './user.entity';
#Injectable()
export class UserService {
constructor(
#InjectRepository(User) private usersRepository: Repository<User>,
#InjectRepository(Role) private rolesRepository: Repository<Role>
){}
getUserById(id): Promise<User> {
return this.usersRepository.findOneOrFail(id);
}
getUserByPseudo(pseudo: string): Promise<User> {
return this.usersRepository.findOne({pseudo});
}
getListRole(): Promise<Role[]> {
return this.rolesRepository.find();
}
getListUser(): Promise<User[]> {
return this.usersRepository.find();
}
getUserByRole(role): Promise<User[]> {
return this.usersRepository.find({where: {role: role}});
}
createUser(data: AuthDto){
const user = {
pseudo: data.username,
password: data.password,
pointEffort: 10,
scienceTab: [],
inventaire: [],
technologieTab: [],
role: {
id: 1,
nom: "joueur",
users: []
},
};
const result = this.usersRepository.save(user);
return result;
}
}
user.entity.ts
import { Place } from "src/place/place.entity";
import { Science } from "src/science/science.entity";
import { TechnologieUser } from "src/technologie/technologieUser.entity";
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { Role } from "./role.entity";
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: Number;
#Column()
pseudo: String;
#Column()
password: String;
#Column()
pointEffort: Number;
#ManyToOne(type => Role, role => role.users)
role: Role;
#ManyToMany(type => Science, science => science.users)
scienceTab: Science[];
#OneToMany(type => TechnologieUser, technologieUser => technologieUser.user)
technologieTab: TechnologieUser[];
#OneToMany(type => Place, place => place.user)
inventaire: Place[];
}
role.entity.ts
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./user.entity";
#Entity()
export class Role {
#PrimaryGeneratedColumn()
id: Number;
#Column()
nom: String;
#OneToMany(type => User, user => user.role)
users: User[];
}
But when i use getListRole() i only get this
And so i don't have the list of my users returned in the property role.users which is missing.
So the question is : how can i have role.users added in the data of getListRole()?
Thx a lot
Get role id from params, then do, this.usersRepository.find({ relations: {Role: true}, where: { role: { id: roleId } } })
Have an observable being returned from my service.ts as shown here:
import { Injectable, ErrorHandler } from '#angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from
'#angular/common/http'
import { Observable } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { PokeResponse } from '../PokeResponse';
#Injectable({
providedIn: 'root'
})
export class PokeApiService {
private url = "https://pokemon-go1.p.rapidapi.com/pokemon_stats.json";
constructor(private http:HttpClient) { }
getPokeData(): Observable<PokeResponse> {
return this.http.get<PokeResponse>(this.url,
{
headers : new HttpHeaders({
'x-rapidapi-key': 'a6cef4cbcamsh05b29346394d4a4p1bafacjsn2a92406ac103'
})
})
.pipe(
tap(data => console.log('Pokedata/Error' + JSON.stringify(data))
),
catchError(this.handleError)
);
}
private handleError(err:HttpErrorResponse) {
console.log('PokemonService: ' + err.message);
return Observable.throw(err.message);
}
}
This is my response:
export interface PokeResponse{
list:results[];
results:{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
}[];
}
export interface results{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
}
export class Pokemon implements results{
pokemon_id:number;
pokemon_name:string;
base_attack:number;
base_defense:number;
base_stamina:number;
constructor(_id:number, _name:string, _atk:number, _def:number, _stam:number) {
_id = this.pokemon_id;
_name = this.pokemon_name;
_atk = this.base_attack;
_def = this.base_defense;
_stam = this.base_stamina;
}
}
And this is my component.ts:
import { Component, OnInit } from '#angular/core';
import { PokeApiService } from 'src/app/services/poke-api.service';
import { PokeResponse, results, Pokemon } from 'src/app/PokeResponse';
import { Observable } from 'rxjs';
#Component({
selector: 'app-list-pokemon',
templateUrl: './list-pokemon.component.html',
styleUrls: ['./list-pokemon.component.css']
})
export class ListPokemonComponent implements OnInit {
constructor(private pokeService: PokeApiService) { }
ngOnInit(): void {
this.getPokeDetails();
}
pokeData:PokeResponse;
errorMessage:any;
pokeArray:results;
getPokeDetails() : boolean {
this.pokeService.getPokeData().subscribe(
pokeData => {
this.pokeData=pokeData;
console.table(pokeData);
},
error => this.errorMessage = <any>error
);
return false;
}
}
In my console I'm getting back a console.table of my observable like this
I'm trying to filter out the names of Pokemon which are the same as others, which could also be achieved by just filtering out any of the pokemon_ids as all the stats match regardless of the type.
So far I've tried:
console.log(this.pokeArray);,
using [...Set()], forEach(), and Array.from()
Any help or suggestions on how I can make this question any clearer would be greatly appreciated.
Try this, using filter:
// list-pokemon.component.ts
export class ListPokemonComponent implements OnInit {
uniqueListPoke = [];
flags = {};
constructor(private pokeService: PokeApiService) { }
ngOnInit(): void {
this.getPokeDetails();
}
pokeData:PokeResponse;
errorMessage:any;
pokeArray:results;
getPokeDetails() : boolean {
this.pokeService.getPokeData().subscribe(
pokeData => {
this.uniqueListPoke = pokeData.filter((entry) => {
if (this.flags[entry.pokemon_name]) {
// console.log('flags', false);
return false;
}
this.flags[entry.pokemon_name] = true;
return true;
});
console.log(JSON.stringify(this.uniqueListPoke));
},
error => this.errorMessage = <any>error
);
return false;
}
}
The working example:
https://stackblitz.com/edit/angular-distinct-poke?file=src/app/hello.component.ts
I have a Observable.timer function that creates a countdown and I want to call a specific function called endTimer() when the timer has ended inside my #Component without using setTimeout(). I can check the value of counter == 0 in the view but how do I check in the #Component
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';
import { Storage } from '#ionic/storage';
import { Observable } from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'
//imported pipes
import {FormatTimer} from '../../pipes/formattimer';
#Component({
selector: 'page-livegame',
templateUrl: 'livegame.html',
pipes: [FormatTimer]
})
export class LivegamePage {
gamesData: any;
countDown: any;
counter = 1*60;
tick = 1000;
constructor(public modalCtrl: ModalController, public navCtrl: NavController, public navParams: NavParams, public storage: Storage) {
//setTimeout(function(){ endTimer(); }, 300000);
}
ionViewDidLoad() {
this.getCurrentGame();
}
ngOnInit() {
this.countDown = Observable.timer(0, this.tick)
.take(this.counter)
.map(() => --this.counter);
}
endTimer() {
console.log('ended');
}
}
<div *ngIf="counter == 0">the timer has ended </div>
Are you subscribing to it somewhere? on the template with 'async' pipe or so? If not, you have to subscribe to it. For the same reason, the variable 'this.counter' will never reach 0.
If you are already subscribing to it on the template with async Pipe, you can use the operator finally:
ngOnInit() {
this.countDown = Observable.timer(0, this.tick)
.take(this.counter)
.map(() => --this.counter)
.finally(() => this.endTimer())
}
if you are not subscribing to it on the template, you can subscribe like this:
ngOnInit() {
this.countDown = Observable.timer(0, this.tick)
.take(this.counter)
.map(() => --this.counter)
.finally(() => this.endTimer())
.share() // Avoid multiple side effect if multiple subscribers
this.countDown.subscribe(() => { /* do nothing */})
}
Hope this helps.
Hello i want to pass the user id (uid) from the home page to a user Details Page. Because i display multiple users on my home page i don’t wan to pass the user session id (as given by the JSON.parse(localStorage.getItem("userData")); ), i want to click on the name of any user on the home page and pass its id and other parameters on the user details page.
home.html
<p (click)="UserPage()" [innerHTML]="item.username | linky"></p>
home.ts
public userDetails: any;
public resposeData: any;
public dataSet: any;
public noRecords: boolean;
rootPage: any = HomePage;
pages: Array<{ title: string, component: any }>;
userPostData = {
uid: “”,
token: “”,
username: “”,
message: “”,
msg_id: “”,
title: “”,
description: “”,
media_pic: “”,
created:""
};
constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menu: MenuController,
public authService: AuthService,
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
) {
const data = JSON.parse(localStorage.getItem("userData"));
this.userDetails = data.userData;
this.userPostData.uid = this.userDetails.uid;
this.userPostData.token = this.userDetails.token;
this.userPostData.username = this.userDetails.username;
this.userPostData.msg_id = this.userDetails.msg_id;
this.userPostData.message = this.userDetails.message;
this.userPostData.title = this.userDetails.title;
this.userPostData.description = this.userDetails.description;
this.userPostData.media_pic = this.userDetails.media_pic;
this.userPostData.created = this.userDetails.created;
this.noRecords = false
this.allArtists();
}
note: this is how i call the users via Auth Service
allArtists() {
this.common.presentLoading();
this.authService.postData(this.userPostData, “newsFeed”).then(
result => {
this.resposeData = result;
if (this.resposeData.friendsNewsFeed) {
this.common.closeLoading();
this.dataSet = this.resposeData.friendsNewsFeed;
console.log(this.dataSet);
} else {
console.log("No access");
}
},
err => {
//Connection failed message
}
);
}
UserPage() {
this.navCtrl.push(UserPage, { uid: this.userPostData.uid });
userProfile.ts
mport { NavController, App, AlertController, MenuController, NavParams } from “ionic-angular”;
export class UserPage {
public uid: string;
constructor(
public common: Common,
public navCtrl: NavController,
public app: App,
public menuCtrl: MenuController,
public navParams: NavParams,
public authService: AuthService
) {
this.uid = navParams.get(‘uid’);
console.log(this.uid);
this.userProfile();
}
}
auth-service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";
//let apiUrl = 'https://api.thewallscript.com/restful/';
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class AuthService {
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
postData(credentials, type){
return new Promise((resolve, reject) =>{
let headers = new Headers();
this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
subscribe(res =>{
resolve(res.json());
}, (err) =>{
reject(err);
});
});
}
}
With NavParams, you doing it the right way already.
It is not visible for me how your item structure is. When you setup your links at your homepage like this: <p (click)="UserPage()" [innerHTML]="item.username | linky"></p>, you could pass the user id of this item into the function like this: UserPage(user.uid).
What happens now, is that your UserPage function already gets the right uid and can pass it to the detailed view.
OK I got the answer. You need to pass the parameters in the with onclick.
home.html
home.ts
UserPage(uid_fk) {
this.navCtrl.push(UserPage, { uid_fk: uid_fk });
console.log(uid_fk);
}
I have to do a mobile application for school and I choosed to use Ionic 2 for this.
I need to display the daily timetable/schedule. For this, I'm using our intranet's API which returns a json, for exemple :
{
"1": [],
"4": {
"matiere": "M4201",
"prof": "LANDRÉ Jérôme",
"salle": "H201",
"evaluation": "N",
"texte": null,
"commentaire": null,
"type": "td",
"fin": 7
},
"7": {
"matiere": "M4204",
"prof": "GOMMERY Patrice",
"salle": "H205",
"evaluation": "N",
"texte": null,
"commentaire": null,
"type": "tp",
"fin": 10
},
"13": {
"matiere": "",
"prof": "",
"salle": "****",
"evaluation": "N",
"texte": "PROJETS",
"commentaire": null,
"type": "CM",
"fin": 19
},
"16": [],
"19": [],
"22": []
}
I successfully retrieve this in my application, but I dont find how to display of list of this.
Here is my /home/home.ts script :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Home } from '../../models/home';
import { HomeCours } from '../../providers/home-cours';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
cours: Home[]
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe(cours => {
console.log(cours)
})
}
}
My /models/home.ts :
/**
* Created by corentin on 17/03/2017.
*/
//récupère la liste des cours sur http://intranet.iut-troyes.univ-reims.fr/api/edtjour/< id de la personne qui consulte >
export interface Home {
matiere: string;
prof: string;
salle: string;
evaluation: string;
texte: string;
commentaire: string;
type: string;
fin: number;
}
My /providers/home-cours.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Home } from '../models/home';
/*
Generated class for the HomeCours provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class HomeCours {
coursApiUrl = 'https://api.corentincloss.fr/intranet/edt.php?id=';
constructor(public http: Http) {
console.log('Hello HomeCours Provider');
}
load(): Observable<Home[]> {
return this.http.get(`${this.coursApiUrl}closs006`).map(res => <Home[]>res.json());
}
}
and finally my home.html :
<ion-header>
<ion-navbar>
<ion-title>Mes cours</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Emploi du temps du jour.</h2>
<hr />
<ion-list>
<div ion-item *ngFor="let cour of cours">
<h2>{{ cour.matiere }}</h2>
</div>
</ion-list>
</ion-content>
I'm sure this is coming from the id ("1", "4", "7"...) but I don't find any way to search the datas in those arrays.
If you could help me please it would be great :D
Thank you :)
After you've obtained the data, you should assign it to a property in your class:
export class HomePage {
cours: Home[]
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe(cours => this.cours = cours);
}
}
You can't *ngFor object. You should make an array from object.
export class HomePage {
cours: Home[] = []
constructor(public navCtrl: NavController, private HomeCours: HomeCours) {
HomeCours.load().subscribe((data: any) => for (let key in data) this.cours.push({key: key, value: cours[key]}););
}
}
Finally found, I had to declare a new array named "cours".
Here is my cours.ts :
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { CoursService } from '../../providers/cours-service';
/*
Generated class for the Cours page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-cours',
templateUrl: 'cours.html',
providers: [CoursService]
})
export class CoursPage {
public cours: any;
public heures: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public coursService: CoursService) {
this.loadCours();
console.log(coursService);
}
loadCours(){
this.coursService.load()
.then(data => {
let cours = new Array();
for (let key in data) {
cours.push(data[key]);
}
this.cours = cours;
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CoursPage');
}
}
And now it's perfectly working ! Thank you for your answers :)