ionic 3 provider initialization on ionViewDidLoad - javascript

First of all, sorry if my english isn't perfect, I'm french.
I'm creating a mobil app with Ionic 3 / angular 4.
My data are stored in a local JSON file in "assets/data" and I'm accessing it with a Provider.
I have a homePage with formular with data value for my 'selector/option input' and I request my provider which returns data by filter/sort etc ...
Everything works but ... it's kind of ugly.
For now, I'm actually using a button at the top of my form to initialize my Provider because I'm calling the 'http.get' method in my Provider constructor (Yeah ... I know it's kind of bad).
I'm using this temporary solution while waiting to find a way to initialize my Provider on the splash screen or in 'ionViewDidLoad' Event ...
my Provider constructor :
#Injectable()
export class DataBaseProvider {
capaciteUrl = './assets/data/capacite.json';
mixageUrl = "./assets/data/mixage.json";
mixageData: any;
capaciteData: any;
constructor(public http: Http) {
console.log('dataBase init');
this.http.get(this.capaciteUrl)
.map(res => res.json())
.subscribe( data => this.capaciteData = data.data);
this.http.get(this.mixageUrl)
.map(res => res.json())
.subscribe( data => this.mixageData = data.data);
}
my 'initializer' function in my homePage.ts ( called by button )
init() {
this.dataBase.getDataSelector()
.then(data => {
this.mixage = data['mixage'];
this.capacite = data['capacite'];
this.firstIngredient = this.secondIngredient = data['ingredient'];
})
}
A part of my form :
<ion-select [(ngModel)]="mixageSelector" okText="Select">
<ion-option *ngFor="let mix of mixage" [value]="mix.id"> {{mix.name}} </ion-option>
</ion-select>
Where can I call the Http.get method or How can I rewrite my module to call Http method at loading/splashScreen of my application ? ( I also try to call my getDataSelector() in an ionViewDidLoadEvent() but nothing changes ... )

Related

Angular 4 update view after deleting from http server

This is probably asked, but I am looking for a most efficient way to update view in a component which fetches data from server, taking that I delete an item from the server in other component
service
getAllMessages(): Observable<any> {
return this.http.get('/api/messages/);
}
applyTagToMessage(messageId): Observable<any> {
return this.http.delete('/api/messages/' + messageId)
}
componentA
this.messageService.getAllMessages().subscribe(data = > {
this.messages = data;
})
<div *ngFor="let message of messages">{{message.tags}}</div>
componentB
addTagToMessage(messsageId)
this.messageService.applyTagToMessage(messageId).subscribe(data = > {
alert("success added tag to message")
})
}
<button (click)="addTagToMessage(messageId)"></button>
So the question how to update the componentA which fetches the data from server when I delete the item from server? Should I use async pipe?
You can use an EventEmitter in your service whenever you change/reload your data. Then subscribe to that event in component A.
Handle the deletion/adding of the items in component B through your service.
https://angular.io/api/core/EventEmitter
In my template I do use an async pipe wherever I'm expecting data to change.
<div *ngFor="let exp of model$ | async">
Where model$ is defined as an observable:
private model$: Observable<Experiment[]>;

Getting PUT routes to work in Angular

I'm seeking some wisdom from the Angular community. I am working on a simple project using the MEAN stack. I have set up my back-end api and everything is working as expected. Using Postman, I observe expected behavior for both a GET and PUT routes to retrieve/update a single value - a high score - which is saved in it's own document in its own collection in a MongoDB. So far so good.
Where things go off track is when trying to access the PUT api endpoint from within Angular. Accessing the GET endpoint is no problem, and retrieving and displaying data works smoothly. However, after considerable reading and searching, I am stll unable to properly access the PUT endpoint and update the high score data when that event is triggered by gameplay. Below are the snippets of code that I believe to be relevant for reference.
BACK-END CODE:
SCHEMA:
const _scoreSchema = {
name: { type: String, required: true },
value: { type: Number, "default": 0 }
};
ROUTES:
router
.route('/api/score/:highScore')
.put(scoreController.setHighScore);
CONTROLLER:
static setHighScore(req, res) {
scoreDAO
.setHighScore(req.params.highScore)
.then(highScore => res.status(200).json(highScore))
.catch(error => res.status(400).json(error));
}
DAO:
scoreSchema.statics.setHighScore = (value) => {
return new Promise((resolve, reject) => {
score
.findOneAndUpdate(
{"name": "highScore"},
{$set: {"value": value} }
)
.exec(function(err, response) {
err ? reject(err)
: resolve(response);
});
});
}
ANGULAR CODE:
CONTROLLER:
private _updateHighScore(newHighScore): void {
console.log('score to be updated to:', newHighScore)
this._gameService
.updateHighScore(newHighScore);
}
SERVICE:
updateHighScore(newHighScore: Number): Observable<any> {
console.log(newHighScore);
let url = '/api/score/' + newHighScore;
let _scoreStringified = JSON.stringify({value: newHighScore});
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this._http
.put(url , _scoreStringified, {headers})
.map((r) => r.json());
}
Note that the console.log(newHighScore) in the last block of code above correctly prints the value of the new high score to be updated, it's just not being written to the database.
The conceptual question with PUT routes in angular is this: If the api is already set up such that it receives all the information it needs to successfully update the database (via the route param) why is it required to supply all of this information again in the Angular .put() function? It seems like reinventing the wheel and not really utilizing the robust api endpoint that was already created. Said differently, before digging into the docs, I naively was expecting something like .put(url) to be all that was required to call the api, so what is the missing link in my logic?
Thanks!

Ionic2 create PHP to get data for show in page

I want to know how to create PHP to get data for show home.html
and I get `Error data is not defined
I don't know this correct? please check this. I have not idea to create PHP, I want to set $path to keep my URL.
<ion-content>
<ion-list inset>
<ion-item>
<ion-label>Username</ion-label>
<ion-input [(ngModel)]="data.username" type="text"></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button block (click)="getRepos()">Search</button>
</div>
<ion-card *ngFor="let repo of foundRepos" >
<ion-card-header>
{{ repo.data.name }}
</ion-card-header>
<ion-card-content>
{{ repo.data.description }}
</ion-card-content>
</ion-card>
</ion-content>
.
import { Component } from "#angular/core";
import { NavController } from 'ionic-angular';
import { Http } from '#angular/http';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public foundRepos;
constructor(public http: Http) {
this.data = {}; >>>>>>>data is not defined
data.username = ''; >>>>>data is not defined
this.http = http;
}
getRepos() {
var link = 'http://localhost/github.php';
var data = JSON.stringify({username: this.data.username}); <<<<this.data.username (data is not defined)
this.http.get(link, data) <<<<data is not defined
.subscribe(data => {
this.foundRepos = data.json();
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
}
github.php
<?php
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
if ($username != "") {
$path = "https://api.github.com/users/".$username."/repos";
echo $path ;
}
else {
echo "Empty username parameter!";
}
}
else {
echo "Not called properly with username parameter!";
}
?>
Ah I see.
In your php you're retrieving a value called $postdata. So I assume you want to send the username from your ionic 2 application to your php file.
2 options, you should try them both because I do not understand php so I'm not sure what the right solution is.
But I do know what the problem is. You're making an http.get() call, and you're passing 2 arguments in this. link and data. The GET method is for getting data from your link, not giving it. The http.get takes 2 parameters, the url, in your case named link, and an HttpHeaders object, so not data.
Solution with parameter in http.get
So, as mentioned above, http.get() can't send your data. Unless you add it as a parameter in your URL. Then your typescript would look like this (note: backticks instead of ' ', makes string concatination easier):
var link = `http://localhost/github.php?username=${this.data.username}`;
this.http.get(link).subscribe(data) { .... }
And in php replace
$username = $response->username
with
$username = $_GET['username']
So final typscript looks like this (since php get request returned 403, Github probably disallowed it)
getRepos() {
var link = `localhost/…${this.data.username}`;
this.http.get(link)
.subscribe(data => {
let repoUrl = data.text();
this.http.get(repoUrl).subscribe(githubResponse => {
this.foundRepos = githubResponse.json();
});
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
If anyone is seeking detailed explanation to why we came to this answer, pleek look in the chat below
You have not declared data variable in the class.
export class HomePage {
public foundRepos;
public data;//here
constructor(public http: Http){
this.data = {};
this.data.username = '';//to refer to data in any function always use 'this'
}
//other functions

Refreshing data through constructor in Angular 2 / Ionic 2

I have Ionic 2 app with one view for 3 different data sets. Data are loaded in constructor and based on variable in page params, it's decided which data set to show.
At every successful data call by observable, event handler logs success when data are loaded. But this only works when I click/load view for a first time. If I click for 2nd or any other time, data are not re-loaded (no log). Also, when I just console log anything, it won't show at 2nd+ click.
So I wonder what should I change to load data everytime and how constructor works in this manner.
This is how my code looks like. Jsons are called from namesListProvider.
#Component({
templateUrl: '...',
})
export class ListOfNames {
...
private dataListAll: Array<any> = [];
private dataListFavourites: Array<any> = [];
private dataListDisliked: Array<any> = [];
constructor(private nav: NavController, ...) {
...
this.loadJsons();
console.log('whatever');
}
loadJsons(){
this.namesListProvider.getJsons()
.subscribe(
(data:any) => {
this.dataListFavourites = data[0],
this.dataListDisliked = data[1],
this.dataListAll = data[2]
if (this.actualList === 'mainList') {
this.listOfNames = this.dataListAll;
this.swipeLeftList = this.dataListDisliked;
this.swipeRightList = this.dataListFavourites;
}
else if (...) {
...
}
this.listSearchResults = this.listOfNames;
}, err => console.log('hey, error when loading names list - ' + err),
() => console.info('loading Jsons complete')
)
}
What you're looking for are the Lifecycle events from Ionic2 pages. So instead of using ngOnInit you can use some of the events that Ionic2 exposes:
Page Event Description
---------- -----------
ionViewLoaded Runs when the page has loaded. This event only happens once per page being created and added to the DOM. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewLoaded event is good place to put your setup code for the page.
ionViewWillEnter Runs when the page is about to enter and become the active page.
ionViewDidEnter Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.
ionViewWillLeave Runs when the page is about to leave and no longer be the active page.
ionViewDidLeave Runs when the page has finished leaving and is no longer the active page.
ionViewWillUnload Runs when the page is about to be destroyed and have its elements removed.
ionViewDidUnload Runs after the page has been destroyed and its elements have been removed.
In your case, you can use the ionViewWillEnter page event like this:
ionViewWillEnter {
// This will be executed every time the page is shown ...
this.loadJsons();
// ...
}
EDIT
If you're going to obtain the data to show in that page asynchronously, since you don't know how long would it take until the data is ready, I'd recommend you to use a loading popup so the user can we aware of something happening in the background (instead of showing a blank page for a few seconds until the data is loaded). You can easily add that behaviour to your code like this:
// Import the LoadingController
import { LoadingController, ...} from 'ionic/angular';
#Component({
templateUrl: '...',
})
export class ListOfNames {
...
private dataListAll: Array<any> = [];
private dataListFavourites: Array<any> = [];
private dataListDisliked: Array<any> = [];
// Create a property to be able to create it and dismiss it from different methods of the class
private loading: any;
constructor(private loadingCtrl: LoadingController, private nav: NavController, ...) {
...
this.loadJsons();
console.log('whatever');
}
ionViewWillEnter {
// This will be executed every time the page is shown ...
// Create the loading popup
this.loading = this.loadingCtrl.create({
content: 'Loading...'
});
// Show the popup
this.loading.present();
// Get the data
this.loadJsons();
// ...
}
loadJsons(){
this.namesListProvider.getJsons()
.subscribe(
(data:any) => {
this.dataListFavourites = data[0],
this.dataListDisliked = data[1],
this.dataListAll = data[2]
if (this.actualList === 'mainList') {
this.listOfNames = this.dataListAll;
this.swipeLeftList = this.dataListDisliked;
this.swipeRightList = this.dataListFavourites;
}
else if (...) {
...
}
this.listSearchResults = this.listOfNames;
}, err => console.log('hey, error when loading names list - ' + err),
() => {
// Dismiss the popup because data is ready
this.loading.dismiss();
console.info('loading Jsons complete')}
)
}
The solution is don't do this in the constructor, use ngOnInit() instead. Components are created only once, therefore the constructor will only be called when first created.
Your component class must implement the OnInit interface:
import { Component, OnInit } from '#angular/core';
#Component({
templateUrl: '...',
})
export class ListOfNames implements OnInit {
constructor(...)
ngOnInit() {
this.loadJsons();
}
private loadJsons() {
...
}
}
i'm coming from Angular 2 world, not ionic, but angular 2 has the option to register callbacks on init/destory (ngInit/ngDestory).
try to move initialization to ngInit, save subscription handler, and don't forget to unsubscribe it on destory.
i think your issue related to that you are not unsubscribing.. :\

Angular 2 app base initialization

How can I make basic initialization of my data in app. For example if user logged in and press F5 I need to request current user data from server before all queries starts like get user order etc. In Angular 1 we have .run() directive for this case. How can I solve this problem?
There are several ways to do that:
You could execute some requests before bootstrapping your Angular2 application. Such first requests could rely what you save into the local / session storage.
var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);
http.get('/userdetails').map(res => res.json())
.subscribe(data => {
bootstrap(AppComponent, [
HTTP_PROVIDERS
provide('userDetails', { useValue: data })
]);
});
See this question for more details:
How to bootstrap an Angular 2 application asynchronously
You could extend the HTTP request to transparently get these data when requests are actually executed. This would be a lazy approach.
#Injectable()
export class CustomHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, userDetailsService: UserDetailsService) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return this.userDetailsService.getUserDetails().flatMap((userDetails) => {
return super.request(url, options);
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return this.userDetailsService.getUserDetails().flatMap((userDetails) => {
return super.get(url, options);
});
}
}
implement the UserDetailsDetails this way:
export class UserDetailsService {
constructor(private http:Http) {
}
getUserDetails() {
if (this.userDetails) {
return Observable.of(this.userDetails);
} else {
return this.http.get(...)
.map(...)
.do(data => {
this.userDetails = data;
// Store in local storage or session storage
});
}
}
and register this CustomHttp class this way:
bootstrap(AppComponent, [HTTP_PROVIDERS,
UserDetailsService,
new Provider(Http, {
useFactory: (backend: XHRBackend,
defaultOptions: RequestOptions,
userDetailsService: UserDetailsService) => new CustomHttp(backend, defaultOptions, userDetailsService),
deps: [XHRBackend, RequestOptions, UserDetailsService]
})
]);
See these questions for more details:
Angular 2 - How to get Observable.throw globally
Cache custom component content in ionic 2
Things could also be done at the level of the router outlet if you use routing. It's possible to implement a custom router-outlet that checks security / user details when a route is activated. I think that it's a little further from your need...
See this question for more details:
Angular 2 Cancelling Route Navigation on UnAuthenticate
You could fetch the current user data before you call Angular2's bootstrap(...)
You could also fire an event (using an Observable for example) to notify other that the logged-in user is now known and initiate further requests only after this event was received.

Categories

Resources