IONIC 4 - The event ionViewWillEnter only fires once - firebase

Please, I am building a Sidemenu Ionic app with firebase firestore, when it opens, the app shows my collections and data, but when browsing between pages with sidemenu and returning to the data page, there is no data return nothing, I need to refresh a browser page to see the data again. I already checked the life cycle and the ionViewWillEnter the event only fires once.
import { Component, OnInit } from '#angular/core';
import { Evento, EventoService} from 'src/app/services/evento.service';
import { Router, RouterEvent } from '#angular/router';
import { LoadingController, NavController } from '#ionic/angular';
#Component({
selector: 'app-eventos',
templateUrl: './eventos.page.html',
styleUrls: ['./eventos.page.scss'],
})
export class EventosPage{
eventos: Evento[];
pages = [
{
url: '/menu/eventos',
}
];
selectedPath = '';
constructor(private eventoService: EventoService, private router: Router,
private loadingController: LoadingController, private navCtrl: NavController) {
this.navCtrl.setDirection('root');
}
ionViewWillEnter(){
console.log(' Teste 3: ionViewWillEnter ')
this.eventoService.getAllEventos().subscribe(res => {
this.eventos = res;
let dateString = 'item.data';
let newDate = new Date(dateString);
this.loadEvento();
});
}
async loadEvento() {
const loading = await this.loadingController.create({
message: 'Carregando eventos...',
spinner: 'crescent',
duration: 300
});
return await loading.present();
}
}
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Eventos</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-card class="card" *ngFor="let item of eventos" lines="inset" button [routerLink]="['/detailsEvento', item.id]"
routerdirection="forward">
<ion-card-header>
<ion-card-title class="texto"> {{item.nome}}</ion-card-title>
<ion-card-title class="texto"> Data: {{item.data | date:'dd/MM/yyyy'}}</ion-card-title>
</ion-card-header>
</ion-card>
</ion-content>
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { IonicModule } from '#ionic/angular';
import { EventosPage } from './eventos.page';
import { FontAwesomeModule } from '#fortawesome/angular-fontawesome';
const routes: Routes = [
{
path: '',
component: EventosPage
}
];
#NgModule({
imports: [
FontAwesomeModule,
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes)
],
declarations: [EventosPage]
})
export class EventosPageModule {}
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Evento {
nome: string;
data: string;
horario: string;
local: string;
descricao: string;
}
#Injectable({
providedIn: 'root'
})
export class EventoService {
private eventosCollection: AngularFirestoreCollection<Evento>;
private eventos: Observable<Evento[]>;
constructor(db: AngularFirestore) {
this.eventosCollection = db.collection<Evento>('eventos', ref => ref.orderBy('data'));
this.eventos = this.eventosCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return{ id, ...data };
});
})
);
}
getAllEventos(){
return this.eventos;
}
getEvento(id){
return this.eventosCollection.doc<Evento>(id).valueChanges();
}
}

constructor(
private afStore: AngularFirestore,
private router: Router,
) {
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd && this.router.url === '/main-screen/home')
{
this.storage.get('userInfo').then((val) => {
if (val) {
// console.log(val);
this.profesion = val.Profesion ? val.Profesion : 'popular';
if ( this.profesion === 'popular') {
this.allCollectionVideo();
} else {
this.getDefaultProfesion(this.profesion);
}
}
});
}
});
}
It can resolve your issue.

Related

Fetch data from asp.net into highchart

I'm trying to make an application with highchart and asp.net and I followed several tutorials and applications because it's a new thing for me.
But I don't know how to fetch data from asp.net into highcharts.js. I tried to do a getChartData function following one video and then I realised that is for chart.js.Can you give me a idea?
This is my code:
bar-chart.ts
import { Component, OnInit } from '#angular/core';
import * as Highcharts from 'highcharts';
import { SalesDataService } from '../../services/sales-data.service';
import * as moment from 'moment';
#Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent implements OnInit {
constructor(private _salesDataServices:SalesDataService ){}
orders:any;
orderLabels:string[];
orderData:number[];
public barChartLabels:string[];
public barChartData:any[];
title = 'myHighChartsApp';
highcharts = Highcharts;
public options: any ={
chart : {
type: "column"
},
title: {
text: "Monthly Sales Chart Department Wise"
},
xAxis:{
},
yAxis: {
title:{
text:"Sales in Million $"
}
},
series: []
}
ngOnInit() {
}
getChartData(res:Response){
this.orders=res['page']['data'];
const data=this.orders.map(o =>o.total);
const formattedOrders=this.orders.reduce((r,e) => {
r.push([moment(e.placed).format('YY-MM-DD'),e.total]);
return r;
},[]);
const p=[];
console.log('formattedOrders:',formattedOrders);
const chartData=formattedOrders.reduce((r,e)=>{
const key=e[0];
if(!p[key]){
p[key]=e;
r.push(p[key]);
}else {
p[key][1]+=e[1];
}
return r;
},[]);
return chartData;
}
}
sales-data-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs';
import { Order } from '../shared/order';
#Injectable({
providedIn:'root'
})
export class SalesDataService {
constructor(private _http: Http) { }
getOrders( pageIndex: number, pageSize: number
) {
return this._http.get('http://localhost:5103/api/order/'+ pageIndex + '/' + pageSize
)
.map(res => res.json());
}
}

In ionic how to set storage to login information so when restarting the app takes directly to the home page

I am using the ionic framework. How do I set storage to login information so if the app restart the user can go to the home page when filling the login information again and again.
import * as firebase from 'firebase/app';
import { Storage } from '#ionic/storage';
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(public storage: Storage) {}
loginUser(value){
firebase.auth().signInWithEmailAndPassword(value.email, value.password)
.then(() => {
console.log('Log In Successful, UID: ' + value.uid + 'Email: ' +
value.email);
this.storage.set('Email', value.email);
this.storage.set('Password', value.password);
})
}
}
Ref. My github Url
authentication.service.ts
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
import { ToastController, Platform } from '#ionic/angular';
import { BehaviorSubject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
authState = new BehaviorSubject(false);
constructor(
private router: Router,
private storage: Storage,
private platform: Platform,
public toastController: ToastController
) {
this.platform.ready().then(() => {
this.ifLoggedIn();
});
}
ifLoggedIn() {
this.storage.get('USER_INFO').then((response) => {
if (response) {
this.authState.next(true);
}
});
}
login() {
var dummy_response = {
user_id: 'manzoor.alam#thinktac.com',
user_name: 'manzoor'
};
this.storage.set('USER_INFO', dummy_response).then((response) => {
this.router.navigate(['dashboard']);
this.authState.next(true);
});
}
logout() {
this.storage.remove('USER_INFO').then(() => {
this.router.navigate(['login']);
this.authState.next(false);
});
}
isAuthenticated() {
return this.authState.value;
}
}
In auth-guard.service.ts
import { Injectable } from '#angular/core';
import { AuthenticationService } from './authentication.service';
import { CanActivate } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor( public authenticationService: AuthenticationService) { }
canActivate(): boolean {
return this.authenticationService.isAuthenticated();
}
}
App.component.ts file
import { Component } from '#angular/core';
import { Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AuthenticationService } from './services/Authentication.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private router: Router,
private authenticationService: AuthenticationService
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.authenticationService.authState.subscribe(state => {
if (state) {
this.router.navigate(['dashboard']);
} else {
this.router.navigate(['login']);
}
});
});
}
}
In app-routing.module.ts
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
import { AuthGuardService } from './services/auth-guard.service';
const routes: Routes = [
// { path: '', redirectTo: 'home', pathMatch: 'full' },
// { path: 'home', loadChildren: './home/home.module#HomePageModule' },
// { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
// { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardPageModule' },
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{
path: 'dashboard',
loadChildren: './dashboard/dashboard.module#DashboardPageModule',
canActivate: [AuthGuardService]
// Here canActivate is a method inside the AuthGuardService which return boolen type values
}
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
Please Ref. My github url more details github Url
Use Router Guard.
A Guard is just an Angular service - or injectable - that controls the behavior of the router in a maintainable way. Let’s generate it with the CLI:
ionic generate guard guards/login
The guard contains a special canActivate method that we are required to implement that must return or resolve to a boolean value. Because Ionic Storage is Promise-based, we can just make it an async function. Its job is to read the loginComplete value from the device storage. If true it allows the route to active, but if false it will block the route and redirect to the login.
// ...omitted
import { Storage } from '#ionic/storage';
#Injectable({
providedIn: 'root'
})
export class LoginGuard implements CanActivate {
constructor(private storage: Storage, private router: Router) {}
async canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {
const isComplete = await this.storage.get('loginComplete');
if (!isComplete) {
this.router.navigateByUrl('/login');
}
return isComplete;
}
}
Applying the Guard
app-routing.module
import { Routes, RouterModule } from '#angular/router';
import { LoginGuard } from './guards/login.guard';
const routes: Routes = [
{
path: '',
loadChildren: './tabs/tabs.module#TabsPageModule',
canActivate: [LoginGuard] // <-- apply here
},
{
path: 'login',
loadChildren: './login/login.module#LoginPageModule'
}
];
#NgModule(...)
export class AppRoutingModule {}
Login page
import * as firebase from 'firebase/app';
import { Storage } from '#ionic/storage';
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(public storage: Storage) {}
loginUser(value){
firebase.auth().signInWithEmailAndPassword(value.email, value.password)
.then(() => {
console.log('Log In Successful, UID: ' + value.uid + 'Email: ' +
value.email);
this.storage.set('Email', value.email);
this.storage.set('Password', value.password);
this.storage.set('loginComplete', true);
})
}
}
Hope it helps you :)
Ref url: AngularFirebase

Angular 6, Firebase Storage web Image gallery

I've got a problem with downloading URL during uploading an image file.
I want to use this url to show this images from Firebase storage.
Uplad is working, because i can see this photos on my storage on firebase, but i can't download it and show in my web
Here's a upload.service.ts
import { Injectable } from '#angular/core';
import { AngularFireModule } from 'angularfire2';
import { GalleryImage } from '../models/galleryImage.model';
import { AngularFireDatabase} from 'angularfire2/database';
import { FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
import { Upload } from '../models/upload.model';
import * as firebase from 'firebase';
#Injectable()
export class UploadService {
private basePath = '/uploads';
private uploads: FirebaseListObservable<GalleryImage[]>;
constructor(private ngFire: AngularFireModule, public db: AngularFireDatabase) { }
uploadFile(upload: Upload) {
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`${this.basePath}/${upload.file.name}`)
.put(upload.file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
// three observers
// 1.) state_changed observer
(snapshot) => {
// upload in progress
upload.progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
console.log(upload.progress);
},
// 2.) error observer
(error) => {
// upload failed
console.log(error);
},
// 3.) success observer
(): any => {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
upload.url = downloadURL;
console.log('FirstURL', downloadURL);
console.log('SecondURL', upload.url);
this.saveFileData(upload);
});
}
);
}
private saveFileData(upload: Upload) {
this.db.list(`${this.basePath}/`).push(upload);
console.log('File saved at' + upload.url);
}
}
Here's my image.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { FirebaseApp } from 'angularfire2';
import 'firebase/storage';
import { GalleryImage } from '../models/galleryImage.model';
import * as firebase from 'firebase';
#Injectable()
export class ImageService {
private uid: string;
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
this.afAuth.authState.subscribe(auth => {
if (auth !== undefined && auth !== null) {
this.uid = auth.uid;
}
});
}
getImages(): Observable<GalleryImage[]> {
return this.db.list('uploads').valueChanges();
}
getImage(key: string) {
return firebase.database().ref('uploads/' + key).once('value')
.then((snap) => snap.val());
}
}
Here's my upload.model.ts
export class Upload {
$key: string;
file: File;
url: string;
progress: number;
createdOn: Date = new Date();
name: string;
constructor(file: File) {
this.file = file;
}
}

Angular-Redux Epics

Getting the following error message in console when using the angular-redux library. Also, Redux won't catch or listen for actions after the error occurs. I've searched, including the documentation but nothing points out to fix the error.
Am I missing something?
Error
core.js:1427 ERROR Error: Actions must be plain objects. Use custom middleware for async actions.
at Object.performAction (<anonymous>:3:2312)
at liftAction (<anonymous>:2:27846)
at dispatch (<anonymous>:2:31884)
at eval (createEpicMiddleware.js:67)
at SafeSubscriber.dispatch [as _next] (applyMiddleware.js:35)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)
at Subscriber.next (Subscriber.js:92)
at SwitchMapSubscriber.notifyNext (switchMap.js:127)
Here's code
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { select } from '#angular-redux/store';
import { ScheduleActions } from '../store/actions'
#Component({
selector: 'app-page2',
templateUrl: './page2.component.html',
styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit {
#select(['schedule', 'scheduleList']) values: any;
constructor(public actions: ScheduleActions) { }
ngOnInit() {
this.actions.loadSchedule();
}
}
Actions
//schedule-actions.ts
import { Injectable } from '#angular/core';
import { NgRedux } from '#angular-redux/store';
import { Schedule } from '../../model/schedule.model';
#Injectable()
export class ScheduleActions {
static readonly LOAD_SCHEDULE = 'LOAD_SCHEDULE';
static readonly LOAD_SCHEDULE_SUCCESS = 'LOAD_SCHEDULE_SUCCESS';
constructor(private ngRedux: NgRedux<any>){}
loadSchedule(){
this.ngRedux.dispatch({
type: ScheduleActions.LOAD_SCHEDULE
});
}
}
Reducer
//schedule-reducer.ts
import { ScheduleActions } from '../actions';
export interface SCHEDULE_STATE {
scheduleList: any,
scheduleDetail: any
}
const initialState: SCHEDULE_STATE = {
scheduleList: [],
scheduleDetail: {}
}
export const ScheduleReducer = (state: SCHEDULE_STATE = initialState, action): SCHEDULE_STATE => {
switch(action.type){
case ScheduleActions.LOAD_SCHEDULE_SUCCESS:
return {...state, scheduleList: action.payload };
case ScheduleActions.LOAD_SCHEDULE_DETAIL_SUCCESS:
return {...state, scheduleList: action.payload };
case ScheduleActions.CREATE_SCHEDULE_SUCCESS:
return {...state, scheduleDetail: action.payload };
default:
return state;
}
}
Epics
//schedule-epic.ts
import { Injectable } from '#angular/core';
import { ActionsObservable, ofType } from 'redux-observable';
import { ScheduleService } from '../services';
import { ScheduleActions } from '../actions';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class ScheduleEpic {
constructor(private service: ScheduleService,
private actions: ScheduleActions
){}
loadScheduleEpic = (action$: ActionsObservable<any>) => {
return action$.ofType(ScheduleActions.LOAD_SCHEDULE)
.mergeMap(action => {
return this.service.loadSchedule().map(result => {
this.actions.loadScheduleSuccess(result)
})
})
}
}
Service
//schedule-service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Schedule } from '../../model/schedule.model';
#Injectable()
export class ScheduleService {
private API_URL: String = "http://mockserver.io/v2";
constructor(private http: HttpClient){}
loadSchedule(){
return this.http.get(this.API_URL + '/5a6225153100004f2bde7f27').map(res => res)
}
}
That error means you dispatched something that was not an action--in this case, your epic emitted something that wasn't an action.
Thankfully, it's an easy fix! You're just missing a return statement in your map
return this.service.loadSchedule().map(result => {
this.actions.loadScheduleSuccess(result)
})
// change it to this:
return this.service.loadSchedule().map(result => {
return this.actions.loadScheduleSuccess(result)
})

Unable to broadcast messages from http extender class to App Component in Angular 2

project Structure
Error Information
This is the error i am getting , when i broadcast the message from http extender service to the app component.
Loading Interceptor(http extender)
this is my http extender ,i am unable to broadcast the messages to App component from here ,but i am able to broadcast the messages from the child components to App component ,please see the image for the error information and project structure
import { Injectable } from '#angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { EventsEmitter } from './eventsEmitter';
#Injectable()
export class LoadingInterceptor extends Http {
private currentRequests: number = 0;
public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private eventsEmitter: EventsEmitter) {
super(_backend, _defaultOptions);
}
public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.incrementRequestCount();
var response = super.get(url, options);
response.subscribe(null, error => {
this.decrementRequestCount();
}, () => {
this.decrementRequestCount();
});
return response;
}
private decrementRequestCount() {
if (--this.currentRequests == 0) {
this.eventsEmitter.broadcast('loading-complete');
}
}
private incrementRequestCount() {
if (this.currentRequests++ == 0) {
this.eventsEmitter.broadcast('loading-started');
}
}
}
App Component
I am listening the events broadcasted in the app component to show the loader gif on the screen
import { Component } from '#angular/core';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterService } from 'angular2-toaster';
#Component({
selector: 'my-app',
templateUrl:'app/app.component.html'
})
export class AppComponent {
private toasterService: ToasterService;
private message: any;
private active: any;
constructor(toasterService: ToasterService, private eventsEmitter: EventsEmitter) {
this.toasterService = toasterService;
this.eventListners();
}
eventListners() {
this.eventsEmitter.on<string>('loading-complete')
.subscribe(message => {
this.active = false;
});
this.eventsEmitter.on<string>('loading-started')
.subscribe(message => {
this.active = true;
});
}
}
Event Emitter
this is the event emittter i am using to broadcast the events
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
interface EventsEmitterInterface {
key: any;
data?: any;
}
export class EventsEmitter {
private _eventBus: Subject<EventsEmitterInterface>;
constructor() {
this._eventBus = new Subject<EventsEmitterInterface>();
}
broadcast(key: any, data?: any) {
this._eventBus.next({ key, data });
}
on<T>(key: any): Observable<T> {
return this._eventBus.asObservable()
.filter(event => event.key === key)
.map(event => <T>event.data);
}
}
App Module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { HttpModule, JsonpModule, Http, RequestOptions, XHRBackend, RequestOptionsArgs, Response, ConnectionBackend} from '#angular/http';
import { AppRoutingModule } from './app.routes';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { LoadingInterceptor } from './assets/scripts/services/loadingInterceptor';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterModule, ToasterService } from 'angular2-toaster';
#NgModule({
imports: [AppRoutingModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, JsonpModule, ToasterModule ],
declarations: [AppComponent, LoginComponent],
bootstrap: [AppComponent],
providers: [EventsEmitter,LoadingInterceptor,
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, eventsEmitter: EventsEmitter) => new LoadingInterceptor(xhrBackend, requestOptions, eventsEmitter),
deps: [XHRBackend, RequestOptions]
},{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppModule { }
I am stuck here for many days, it would be really helpful if you could help me resolve this issue
You forgot to add EventsEmitter dependency within your useFactory provider:
deps: [XHRBackend, RequestOptions]
It shoul be:
deps: [XHRBackend, RequestOptions, EventsEmitter]
That's why your LoadingInterceptor constructor gets undefined for EventsEmitter dependency

Resources