Ionic 3: How make ionViewWillEnter only when back button pressed? - ionic-framework

I have read Navigating Lifecycle Events
My use case here is. I had to refresh the content on page load as well as when back button pressed from another page.
ionViewDidLoad(){
this.getProjects();
}
ionViewWillEnter(){
this.getProjects();
}
this works fine but of course ionViewWillEnter runs on first page load as well. so two api requests triggered (ionViewDidLoad + ionViewWillEnter). Is there any way to restrict them like setting flag or something?

You can use events for this purpose. Whenever user clicks back button, publish the event like this:
onBackButtonPressed(){
this.events.publish('backPressed');
}
subscribe to this event from the page where you want to refresh the data:
constructor(public events: Events) {
events.subscribe('backPressed', () => {
this.getProjects();
});
}
Refer this: https://ionicframework.com/docs/v3/api/util/Events/
The problem with this issue is you have to publish the event from all the pages to which the navigation is possible from the current page.

use this:
ionViewDidLoad()
{
this.navBar.backButtonClick = this.onClickBackButton.bind(this);
}
onClickBackButton(event)
{
}

Related

How can i handle popups in playwright-java?

How can i handle alerts and popups in playwright-java?
there are different methods in API like page.onDialog(), page.onPopup(), what is the difference between them and how can i generate a handle?
//code to launch my browser and url
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new LaunchOptions().withHeadless(false).withSlowMo(50));
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("http://myurl.com");
//had to switch to iframe to click on upload button
Frame mypage = page.frameByName("uploadScreenPage");
//below line is triggering the alert
mypage.setInputFiles("//*[#id='fileUpload']",Path.of("C:\\myFile.jar"));
//using this code to handle alert, which is not working
page.onDialog(dialog -> {dialog.accept();});
unable to accept alert using the above code. also alert has occurred after clicking an element that is inside an iframe. how can i handle such alerts?
Dialogs are messages like an alert or a confirm, whereas popups are new pages, like the one you would get by calling window.open.
This is how you can use it :
page.onDialog(dialog -> {
assertEquals("alert", dialog.type());
assertEquals("", dialog.defaultValue());
assertEquals("yo", dialog.message());
dialog.accept();
});
page.evaluate("alert('yo')");
I am happy to answer this question. I encountered the same situation and find the solution. Please see below:
//Handling Pop-up or new page
Page pgdriver1 = pagedriver.waitForPopup(new Runnable()
{
public void run() {
pagedriver.click("text=\"Analiza\"");
}
});
pgdriver1.click("//button[normalize-space(#aria-label)=\"Close dialog\"]/nx-icon");
I hope this answer your question.
//listening to the alert
page.onDialog(dialog -> {dialog.accept();});
//next line will be action that triggers your alert
page.click("//['clickonsomethingthatopensalert']")

How to open a modal in Ionic 5 automatically, just after loading of the page?

I'd like to open a modal in Ionic 5 just opening a page. Without any action, just load the page and hop! you get your modal.
I've been reading the documentation at https://ionicframework.com/docs/api/modal#events but is too cryptic for me. Need some more elaboration...
I´ve fount severals examples out there of opening the modal with a click event, but that's not what I need.
Thanks in advance!
Look into Ionic's lifecycle hooks which let you execute code at different moments during a component's existence. You'll probably want to call a modal creating method inside of the ionViewDiDEnter hook within the component where you want the modal to appear.
Something like this:
export class YourPage {
constructor(public modalController: ModalController) { }
ionViewDidEnter() {
this.presentModal();
}
async presentModal() {
const modal = await this.modalController.create({
component: YourModalComponent
});
return await modal.present();
}
}

Events provider is deprecating. Using Redux or Observables for state in ionic apps

I've been using events in my ionic application, where i subscribe in one page, and publish the event in the other page. Now I see a warning that Events are going to be changed with Observables and Redux state and effect.
I was using Events mainly to call for component function changes outside it, so I had a components for example:
Component1.ts
this.events.subscribe('event:addValue1', (data: any) => {
this.valueName = 'VALUE1';
});
this.events.subscribe('event:addValue2', (data: any) => {
this.valueName = 'VALUE2';
});
and than outside this component I was calling the publish methods from any page, like:
Page1.ts
this.events.publish('event:addValue1');
Page2.ts
this.events.publish('event:addValue2');
By this i was able to change the data (this.valueName) outside the Component1.ts from any other page, simply by publishing the desired event.
I know that this might not sound or be right approach, but It was the only way I was doing changes to my Component1.ts outside it from any page.
I have now changed this and just put separate functions and than i access them via ViewChild component name like
#ViewChild('component') component: any;
....
this.component.functionAddValue1().
and additionally I send additional params via Angular NavigationExtras if i need to calculate and call some function from the Component1.ts, lets say if I navigate to some route.
Before this I was just calling the events.publish and I was able to make the changes to the Component1.ts on the fly.
Create event service.
In the EventService.ts:
export class EventService {
private dataObserved = new BehaviorSubject<any>('');
currentEvent = this.dataObserved.asObservable();
constructo(){}
publish(param):void {
this.dataObserved.next(param);
}
}
For publishing the event from example page1:
constructor(public eventService:EventService){}
updatePost(value){
this.eventService.publish({name:'post:updated',params:value});
}
In page 2:
constructor(public eventService:EventService){
eventService.currentEvent.subscribe(value=>{
if(value.name=='post:updated'){
//get value.name
}else if(value.name=='another:event'){
//get value or update view or trigger function or method...
}
// here you can get the value or do whatever you want
});
}

ionic 4 deal with modal when users click phone back button

What should happen when users click over back button of phone? In case when modal opens.
Registered a back button:
// To prevent interference with ionic's own backbutton handling
// you can subscribe with a low priority instead
this.platform.backButton.subscribe(() => {
// code that is executed when the user pressed the back button
// and ionic doesn't already know what to do (close modals etc...)
self.modalController.dismiss();
});
The problem with the code:
It closes/dismiss modal is fine!
But it also pushed back the page from where the modal is opened. Means it pop the page behind modal.
This should not happen the page should not pop - only modal should close.
Check the image gif added ->
Click here to see the problem
You may consider using platform.backButton.subscribeWithPriority() with a high priority (ex: 9999).
Then checking if there is a opened modal with modalController.getTop().
constructor(private modalCtrl: ModalController, private nav: NavController) {
}
ngOnInit() {
this.platform.backButton.subscribeWithPriority(9999, () => {
this.closeModalOrPage();
});
}
async closeModalOrPage(){
let modal = await this.modalCtrl.getTop();
if (modal){
modal.dismiss();
} else {
this.nav.pop();
}
}

button back to my app in the background and when you resume it starts again

I am developing an app in Xamarin.Forms, before I was trying to make a master detail page to become my MainPage when I logged in to my app, this I have already achieved. Now I have the problem that when I use the button behind the phone my app is miimiza and goes to the background which is the behavior I hope, but when I return to my app does not continue showing my master detail page, but returns to my LginPage.
It is as if my app was running twice or at least there were two instances of LoginPage existing at the same time, this is because in my LoginPage I trigger some DisplayAlert according to some messages that my page is listening through the MessaginCenter and they are they shoot twice.
Can someone tell me how I can return the same to my app on the master detail page and not restart in the strange way described?
LoginView.xaml.cs:
public partial class LogonView : ContentPage
{
LogonViewModel contexto = new LogonViewModel();
public LogonView ()
{
InitializeComponent ();
BindingContext = contexto;
MessagingCenter.Subscribe<LogonViewModel>(this, "ErrorCredentials", async (sender) =>
{
await DisplayAlert("Error", "Email or password is incorrect.", "Ok");
}
);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<LogonViewModel>(this, "ErrorCredentials");
}
}
Part of my ViewModel:
if (Loged)
{
App.token = token;
Application.Current.MainPage = new RootView();
}
else
{
MessagingCenter.Send(this, "ErrorCredentials");
}
Thanks.
I hope this is in Android. All you can do is, you can override the backbuttonpressed method in MainActivity for not closing on back button pressed of the entry page. like below, you can add some conditions as well.
public override void OnBackPressed()
{
Page currentPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentPage != null)
{
if (currentPage.GetType().Name == "HomePage" || currentPage.GetType().Name == "LoginPage")
{
return;
}
}
base.OnBackPressed();
}
When you press the Home button, the application is paused and the
current state is saved, and finally the application is frozen in
whatever state it is. After this, when you start the app, it is
resumed from the last point it was saved with.
However, when you use the Back button, you keep traversing back in
the activity stack, closing one activity after another. in the end,
when you close the first activity that you opened, your application
exits. This is why whenever you close your application like this, it
gets restarted when you open it again.
Answer taken from this answer. The original question asks about the native Android platform, but it still applies here.
It means you have to Use Setting Plugin or save data in Application properties.
You have to add below code in App.xaml.cs file:
if (SettingClass.UserName == null)
MainPage = new LoginPage();
else
MainPage = new MasterDetailPage();
For Setting Plugin you can refer this link.