Angular app routing during bootstrap in iframe - html

I have an angular app running in an iframe. The html looks like this.
<html>
<body>
<iframe src="http://localhost:9999?screen=two"></iframe>
</body>
</html>
In the path provided, I have added a query param 'screen'. There are three views available, routing is shown below.
const routes: Routes = [
{ path: 'one', component: OneComponent },
{ path: 'two', component: TwoComponent },
{ path: '', component: AppComponent }
];
Within the angular app, I have resolved the component to be shown in ngOnInit() of app.component.ts
ngOnInit(): void {
const screen = this.activatedRoute.snapshot.queryParams['screen'];
console.log('main component loaded.');
console.log(screen);
this.router.navigate([screen]);
}
The problem is, the iframe always shows OneComponent until, I re-open the tab after changing the query param.
My questions are:
Why does this happen?
Is there a way I can make the screen change
after only changing the query param and reloading, instead of
reopening the tab?

I am not sure about the why but there is a fix to refresh the iframe automatically every time the query param changes.
<script>
var _theframe = document.getElementById("theframe");
theframe.contentWindow.location.href = theframe.src;
</script>

Related

How to navigate in React-Native?

I am using ReactNavigation library in my react-native project and since 6 hours I am trying to navigate from one screen to others screen and have tried every possible way but I think I am not able to get the logic properly.
This is my project structure.
Here
The way I am doing it.
const AppStack = StackNavigator({ Main: Feeds });
const AuthStack = StackNavigator({ Launch: LaunchScreen, });
export default SwitchNavigator({
Auth: AuthStack,
App: AppStack
});
In my LaunchScreen.js
const SimpleTabs = TabNavigator(
{
Login: {
screen: Login,
path: ""
},
SignUp: {
screen: SignUp,
path: "doctor"
}
},
);
<SimpleTabs screenProps={{rootNavigation : this.props.navigation }}/>
But the problem is in my LaunchScreen Component there is a TabNavigator which contains my other two components Login.js and SignUp.js but the button in my Login.js doesn't navigate it to Feed.js.
When you click on the button this is performed.
signInAsync = async () => {
await AsyncStorage.setItem('userToken', 'abc');
this.props.navigation.navigate('Main');
console.log("AAAAAsSSS");
};
My LaunchScreen.js contains a TabNavigation which lets you slide between two components ie. Login.js and SignUp.js.
Now when you click on the Login button which is in Login.js component it will authenticate the user and will switch the entire LauchScreen.js component with the Feed.js component.
I am a noob to react-native.
You can use react-native-router-flux (npm install --save react-native-router-flux)
just make one Navigator.js file and define each page you wanted to navigate.
import React from 'react';
import { Router, Scene } from 'react-native-router-flux';
import LaunchScreen from '../components/LaunchScreen.js';
import Feed from '../components/Feed.js';
const Navigator = () => {
return (
<Router>
<Scene key="root">
<Scene key="lauchscreen" component={LaunchScreen} hideNavBar initial />
<Scene key="feedscreen" type="reset" hideNavBar component={Feed} />
</Scene>
</Router>
);
};
export default Navigator;
now in your App.js file add this:
import Navigator from './src/Navigator.js';
export default class App extends Component<Props> {
render() {
return (
<Navigator />
);
}
}
now in your login.js when you click on login button write this:
import { Actions } from 'react-native-router-flux';
onLoginClick() {
Actions.feedscreen();
}
Thats it.. happy coding.
If you want to navigate to Feeds.js then navigate as
this.props.navigation.navigate('App');
not as
this.props.navigation.navigate('Main');
because your
export default SwitchNavigator({
Auth: AuthStack,
App: AppStack // here is your stack of Main
});
refer example
I came across the same issue few months ago. Thank god you have spent just 6 hours, i almost spent around 4 days in finding a solution for it.
Coming to the issue, Please note that in react-navigation you can either navigate to siblings or children classes.
So here, You have a swtichNavigator which contain 2 stack navigators (say stack 1 and stack 2), stack1 has feeds and stack2 has a tab navigator with login and signup.
Now you want to navigate from login.js to feeds.js(say file name is feeds.js). As mentioned already you can not navigate back to parent or grandparent. Then how to solve this issue?
In react native you have the privilege to pass params (screenprops) from parent to children. Using this, you need to store this.props.navigation of launchScreen into a variable and pass it to tab/login (check the tree structure). Now in the login.js use this variable to navigate.
You are simply passing the navigating privilege from parent to children.
Editing here:
<InnerTab screenProps={{rootNavigation : this.props.navigation }} />
Here, InnerTab is the tab navigator.
export const InnerTab = TabNavigator({
login: {
screen: login,
},
},
signup: {
screen: signup,
},
},
},
in login class, use const { navigate } = this.props.screenProps.rootNavigation;
Now you can use variable navigate.
I know its little tricky to understand but i have tried and it works.
Write your Navigator.js file as below,
import React from 'react'
import { NavigationContainer, useNavigation } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
const SwitchNavigatorStack = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='{nameofscreen}' screenOptions={screenOptions}>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
<Stack.Screen name='{nameofscreen}' component={{nameofscreen}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default SwitchNavigatorStack
Once, you are done with that change your App.js file to,
import SignedInStack from './navigation'
import React from 'react'
export default function App() {
return <SwitchNavigatorStack/>
}
After this, you are done with setting your project for navigating. In all the components where you want to add navigation feature make sure you use the navigation.navigate() (or) navigation.push() method. Also make sure you hook navigation constant by import useNavigation library. For example,
const Login = () => {
const navigation = useNavigation()
< Button title = 'Login' onPress={() => navigation.navigate('{nameofscreen}')} />
}
with this code snippet you can implement navigation between screens using #react-navigation/native and #react-navigation/stack

Angularjs - Append html code to body when URL changes

I'm working on single page aplication based on Angular. I want to do something like card stack made from divs. Like this.
Idea is that app will have some url links and card should be append when url changes. For example I have 4 links. Home | About | Contacts | Details
On page load will append home card then About etc. So url will change and next card should append.
So my question is: how append some html block when url changes in Angular? I mean that url will be changed but view should be the same and I want just append some html to existing view
Thanks
If using ui.router you can do it like this and update the scopes with the images.
Here is a code example
'use strict';
angular
.module('myApp', [
'ui.router'
])
.config(function ($locationProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
// define states
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home.html'
})
.state('about', {
url: '/about',
templateUrl: 'views/about.html'
});
// define alternative route
$urlRouterProvider.otherwise('/');
})
.run(function ($rootScope) {
// image changes with route change
if(toState.url === '/') {
$rootScope.headerImg = 'images/headers/home.jpg';
} else if (toState.url === '/about') {
$rootScope.headerImg = 'images/headers/about.jpg';
} else {
$rootScope.headerImg = 'images/headers/error.jpg';
}
});
});

Store HTML page in memory with Angular2

I would like to keep web page in memory so that when I click on back button (not the one on web browser) or on a routerlink, the HTML page instantly loads if I already visit it(because I have some data to load that I don't want to be reload).
I've seen a method with tabbed interface : https://www.w3.org/Style/Examples/007/target.en.html#tab1
but it is not adapted for my code architecture.
I'm using routerlinkin angular2 to navigate threw pages and a back button calling a function on click to go to the previous page.
I try to detail as far as I can so people can understand better my code architecture and the way routerlink method works.
Back button function (works independently from routerlink) :
goBack() {
window.history.back();
}
The router link method from page 1 to page 2:
page1.html :
<a[routerLink]="['PAGE2']"> go to page 2</a>
page1.ts component:
import { Router, ROUTER_DIRECTIVES } from '#angular/router-deprecated';
#Component({
selector: 'page1',
templateUrl: 'page1.html',
styleUrls: ['page1.css'],
directives: [ROUTER_DIRECTIVES]
})
main.ts :
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '#angular/router-deprecated';
#Component({
providers: [ROUTER_PROVIDERS]
})
#RouteConfig([
{ path: '/page2', name: 'PAGE2', component: Page2}]) //component representing class Page2 in page2.ts
Any idea to help me manage it is welcomed, thanks by advance !
Just cache the data in the service like explained in What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?
There is currently no way to prevent the router from re-creating the component when you route away and back to the component.
Well, for those having the same problem, I think the best way to manage it is to map the data into a localStorage key like this :
localStorage.setItem('favoris',JSON.stringify(my_array)); //set my data array
array = JSON.parse(localStorage.getItem('key_name')); //get in array
And then ngOnInitin the class called by the router will call the initial function depending of localStorage key being true or not.

ionic - $state.go with params issue1

I just create the ionic project and I'm trying to make the sign in and sign up page and I just implement the HTML and CSS. but the problem is I can't change position between controllers.
The URL of controller is changes but the page is not changed. I was trying to import the correct module but I can't find the method.
Make sure in app.js, your templateURL , url is properly defined.
Most of the time it might be your 'URL' problem.
If you navigated from 'main', your next url should be : /main/success or something like that.
.state('tab.main', {
cache: false, //if you want to disable cache in ionic
url: '/main',
views: {
'tab-cases': {
templateUrl: 'templates/tab-main.html',
controller: 'MainCtrl'
}
}
})

Generate Page Based on JSON Data

I'm using AngularJS for an app I'm building and was wondering if it's possible to generate pages when items are pushed to a JSON object called places. Each item when pushed is given a unique ID and I figured I could use this id (e.g. 123456) as part of the url like so site.com/places/123456.
{
"places" : [
{
"id" : 471756,
"title" : "The Whittington Hospital"
}
]
}
Is it possible to have this page generated automatically (for example, based on a template)?
I ask because I'm trying to build an app that let's users create their own hospitals via a form. Once a hospital is created and pushed to the JSON object, I'd like a page to be created for that hospital.
Can I use Angular for this? Any help is appreciated.
Thanks in advance!
UPDATE
Still having a bit of trouble with this. Here's what I've got so far.
place.html
<div ng-controller='PlaceCtrl'>
<h1>{{ title }}</h1>
</div>
JS
app.constant('FBURL', 'https://luminous-fire-8685.firebaseio.com/');
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/places/:placeId', {
templateUrl: 'views/place.html',
controller: 'PlaceCtrl'
})
}]);
app.factory('place', function($firebase, FBURL, $routeParams) {
var ref = new Firebase(FBURL + "places/" + $routeParams.placeId);
return {
id: $routeParams.placeId
}
});
app.controller('PlaceCtrl', function($scope, $rootScope, FBURL, $firebase, $location, $routeParams, place) {
$scope.placeId = place.id;
});
You're looking for ngRoute and $routeProvider. With those you can set up a parameterized route like this:
.when('/place/:placeId', { templateUrl: 'place.html', controller: 'PlaceCtrl' })
So every time a visitor hits a URL that starts with /place/ it ends up at PlaceCtrl and place.html. And the place ID is passed as a parameter.
Then you can pick up the parameter in your controller:
app.controller('PlaceCtrl', function($scope, FBURL, $firebase, $routeParams) {
var ref = new Firebase(FBURL+"places/"+$routeParams.placeId);
See also:
My sample application that uses AngularJS, Firebase and AngularFire: https://github.com/puf/trenches/blob/master/app.js (from which I copy/paste/modified the above snippets)
The AngularJS documentation for routeParams
The AngularJS tutorial's step on routing
The (way better) Thinkster.io tutorial page on routeParams