How to go back in Ionic 4 - javascript

I want to add a back button in Ionic4(Angular 7).
But I can't find the proper method in Angular Router.
import {Router} from '#angular/router';
How do we go back when clicking a button, in the component handler?
I'd like to implement it using '#angular/router' not '#angular/common' => Location

Since you are using ionic 4 then to go backward, you can do the following:
constructor(private navCtrl: NavController) {}
btnClick(){
this.navCtrl.navigateBack('/home');
}

With Angular routing you could use the Location API:
constructor(private location: Location){}
and then when you need to navigate back call:
this.location.back();
Keep in mind that for Angular 7 you have to import Location from #angular/common

Just do the following if you wanna go back to your previous route.
constructor(private navCtrl: NavController) {}
goBack(){
this.navCtrl.pop();
}
This'll pop the current page from the navigation stack and return you to the previous page and the part of the page from where you had navigated forward.

Related

How to reload a component in Angular without reloading the whole page

I want to reload a route but without reloading the entire page. This is not what I want:
window.location.reload();
I want to reload just the component not the page. This is waht I tried:
Angular: Change the route without reloading
Angular: Refetch data on same URL navigation
Some other random tricks also I tried. Tried following code from this URL:
Angular Basics: Refresh an Angular Component without reloading the same Component
mySubscription: any;
constructor() {
this.router.routeReuseStrategy.shouldReuseRoute=function() {
return false;
}
this.mySubscription= this.router.events.subscribe((event)=> {
if(event instanceof NavigationEnd) {
// Trick the Router into believing it's last link wasn't previously loaded
this.router.navigated=false;
}
})
}
But It's not working due to other reasons. I need a solution. Please suggest something else.
the skipLocationChange option works for me,try my service
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
#Injectable()
export class ReloadRouteService {
constructor(
private router: Router,
) { }
redirectTo(url: string): void {
// When skipLocationChange true, navigates without pushing a new state into history.
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([url]);
});
}
}

router.navigate(url) doesn't load the component but typing the url directly into the browser does

I'm trying to load an Angular 8 component by clicking on a div like this:
showMovie(movieId) {
this.router.navigate([`/movie/${movieId}`]);
}
This used to work, and in my deployed version on netlify it still works, but when I try to do it from localhost it doesn't anymore. If I type the url directly in the browser tho, it works just fine.
Try to use this code, using queryParams, I'm not sure about the syntax:
this.router.navigate(['/movie'], {queryParams: {movieId: movieId }})
You can try this:-
At first import router
import { ActivatedRoute, Router } from '#angular/router';
declare router in constructor:
private router: Router,
then,
this.router.navigate(['/movie', movieId]);
thank u

Google authentication screen on click of an app in angular 6

I am building an app in Angular 6 + PWA. I have to implement Google Authentication for logging in. The google login screen should be the first screen when we click on the app icon. I don't want the screen where Google button appears for and on its click the login screen appears. Post successful login, landing page will appear. From what i could gather, only on click of the following button, will the logins screen appears
<div class="g-signin2" data-onsuccess="onSignIn"></div>
When we click on this button, control is given to onSignIn() and then the flow is carried on. I want this function to be called on ngOnInit() of angular
app.component.ts as it is the root component. Basically i don't want the following:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
and yet i want to call its method onSignIn()
How can i achieve this?
In my AuthService I have a method that looks like this:
googleLogin() {
const provider = new auth.GoogleAuthProvider()
return this.oAuthLogin(provider);
}
In the component you want to use this you could do this:
import { Component, OnInit } from
'#angular/core';
import { AuthService } from
'../auth/auth.service';
#Component({
selector: 'user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements
OnInit {
constructor(public auth: AuthService) {
}
ngOnInit() {
this.auth.googleLogin();
}
}
Don't forget to import the AuthService into the component you're using it in.
You may not be using firebase, but just call the method for google login in your particular auth api in either an OnInit function. No need to 'have' to click a button to call the method.

Embedding tracking codes in Angular 2

I'm looking for the best way to implement tracking codes into my Angular 2 app. Not Google Analytics, but 3rd party suppliers like Marketo and others. I need the codes to fire each time I load a component(page). I've tried using the router changes with only partial success (and some unexpected results). Some version of this kind of worked but not fully.
this.router.events.subscribe(() => {
//tracking code goes here
});
Has anyone else had success with 3rd party tracking on Angular2 or other SPAs? Putting the tags in the template files doesn't work. Thanks.
Just use a guard on any route you want to track. It will be called every time the route is activated:
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from "#angular/router";
import {Observable} from "rxjs";
export class TrackingGuard implements CanActivate
{
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean>|boolean
{
console.log(state.url);
console.log(state.queryParams);
return true;
}
}
And in your route definitions where you specify which component for the route just add canActivate: [TrackingGuard] under it. In the above example you will have access to the url and any query params. Would recommend making some other service which makes the request to the tracking api and just call if from the guard.

angular 2: Changing static parts of the view according to path

First of all, sorry for the weird title. I couldn't find a better summary.
So what I want is to create an application which consists of a basic 3 part structure (header / content / footer). Depending on the route that is active, the header part should change (every header is a component on its own).
So far the header that is displayed is determined by an [ngSwitch] statement in the "mainApp.component" and looks like this:
<span [ngSwitch]="currentLocation">
<span *ngSwitchWhen="'/login'"><login-header></login-header></span>
<span *ngSwitchWhen="'/home'"><home-header></home-header></span>
</span>
<div class="content"><router-outlet></router-outlet></div>
<app-footer></app-footer>
Where the "mainApp.component.ts" looks like this:
import { Component, OnInit } from '#angular/core';
import {ROUTER_DIRECTIVES} from '#angular/router';
import {HomeHeaderComponent} from './home-header';
import {LoginHeaderComponent} from './login-header';
import {FooterComponent} from './footer';
import {Router} from '#angular/router';
#Component({
moduleId: module.id,
selector: 'app',
templateUrl: 'mainApp.component.html',
styleUrls: ['mainApp.component.css'],
directives: [HomeHeaderComponent, LoginHeaderComponent, FooterComponent, ROUTER_DIRECTIVES],
providers: []
})
export class mainApp implements OnInit {
public currentLocation: string;
constructor(public router: Router) {
this.currentLocation = location.pathname;
}
ngOnInit() {
}
}
This works just fine when I go to my localhost:4200/login or localhost:4200/home manually as it renders the mainApp.component, checks which is the current route and displays the header accordingly. However, when I change the route by e.g. a button click via
<span class="btn btn-default headerButton homeButton" (click)="navigateToHome()"></span>
Where navigateToHome() is simply
navigateToHome() {
this.router.navigate(['/home']);
}
The header stays the same as the change detection doesn't take the route change into concideration and therefore doesn't rerun the [ngSwitch] / rerender the mainApp.component.
I already thought about including the header inside the components template they belong to but if there is a way to do it in the main component I would prefer that.
If you guys got any idea of how to solve this, or ways to do it better / another way / the way its best practice I'm glad to hear of it.
Thanks.
The answer here is to subscribe to the router events like so:
this.router.events.subscribe((e) => {e instanceof NavigationEnd? this.currentLocation = '/' + e.url.split('/')[1] : ''});
This subscribes to the routers events in general and changes the currentLocation variable whenever the navigation ends succesfully by checking the url property of the returned value.
I implemented this in the (at the time of this post) current router version #angular/routerv3.0.0-alpha8 which works just fine.

Categories