Router Malfunction - html

So I am having an issue with two components which have to do with routers/routing/router-outlets. In my login form when the user enters the info(email and password) and clicks login they should be routed to the dashboard.
See below the login form component and its accompanying ts/css/html files
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Observable} from 'rxjs/Observable';
import { auth } from 'firebase/app';
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
user: Observable<firebase.User>;
authenticated: boolean = false;
error: any;
constructor(private router:Router,public af: AngularFireAuth) {
this.af.authState.subscribe(
//look at this again
(auth) => {
if (auth != null){
this.user = af.authState;
this.authenticated = true;
this.router.navigate(['dashboard']);
}
}
)
}
ngOnInit() {
}
loginUser(e){
e.preventDefault();
console.log(e.value);
var email = e.target.elements[0].value;
var password = e.target.elements[1].value;
console.log(email,password);
this.af.auth.signInWithEmailAndPassword(email,password)
.then((success) => {
console.log(success)
this.authenticated = true;
console.log("attempting to nav");
this.router.navigate(['dashboard']);
console.log("nav worked");
}).catch((err) => {
this.error= err;
})
//end of if statement
}//end of login user
}
HTML for Login Form
<div class="form">
<span class="error" *ngIf="error">{{ error }}</span>
<form (submit) = "loginUser($event)">
<input type="text" placeholder="Email Address"/>
<input type="password" placeholder="Password"/>
<button type = "submit">login</button>
</form>
</div>
HTML for appCompnent that controls the first screen you see which has the login form enclosed
<div id = "fullPage">
<app-header></app-header>
<app-login-form></app-login-form>
<app-footer></app-footer>
</div>
AppModule.ts which contains routes
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { LoginFormComponent } from './components/login-form/login-form.component';
import { FooterComponent } from './components/footer/footer.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import {RouterModule,Routes} from '#angular/router';
import {Router} from '#angular/router';
import { Route } from '#angular/compiler/src/core';
//Firebase configuration
import {AngularFireModule} from 'angularfire2';
import {environment} from '../environments/environment';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import {AngularFireAuthModule} from 'angularfire2/auth';
//Forms
import {FormsModule} from '#angular/forms';
//All Components
import { EventsComponent } from './components/events/events.component';
import { EventDetailsComponent } from './components/event-details/event-details.component';
import { AddEventComponent } from './components/add-event/add-event.component';
import { EditEventComponent } from './components/edit-event/edit-event.component';
import { DeleteEventComponent } from './components/delete-event/delete-event.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { Component } from '#angular/core/src/metadata/directives';
const appRoutes:Routes = [
{
path: 'login',
component: LoginFormComponent
},{
path: 'dashboard',
component: DashboardComponent
},{
path: 'events',
component: EventsComponent
},{
path: 'add-event',
component: AddEventComponent
},{
path: 'edit-event/:id',
component: EditEventComponent
},{
path: 'delete-event/:id',
component: DeleteEventComponent
},{
path: 'event-details',
component: EventDetailsComponent
}
]
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
LoginFormComponent,
FooterComponent,
DashboardComponent,
EventsComponent,
EventDetailsComponent,
AddEventComponent,
EditEventComponent,
DeleteEventComponent,
NavbarComponent
],
imports: [
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(environment.firebase),AngularFirestoreModule,AngularFireAuthModule,
BrowserModule,FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I followed a lot of tutorials so I believe I have done it right. However, it does not go to the dashboard. Any hints? Is it because I don't have a router-outlet in place of the app-login-form?

By the above code snippet, it seems that you have missed "router-outlet" tag which needs to be included in a template from where you try to navigate to the dashboard page. It should resolve your issue.

Related

Migrating from Ionic 3 to Ionic 5 - Json functions on user-data

Hello i am trying to migrate from Ionic Cordova 3 to 5.
I want to put a call a php function to get results. PHP works fine.
this is what i did to call the results.
home.ts
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.map(res => res.json())
.subscribe(data => {
if (data.success) {
this.allMedia = data.mediaFeed;
}
});
}
user-data.ts function
allMedias(offset: number) {
console.log('ddd');
let url = this.appData.getApiUrl() + 'allMedia';
let data = this.jsonToURLEncoded({
api_signature: this.api_signature,
offset: offset
});
return this.http.post(url, data, this.options);
}
this is the error i am getting
core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
app.module.ts
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { InAppBrowser } from '#ionic-native/in-app-browser/ngx';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { IonicModule } from '#ionic/angular';
import { IonicStorageModule } from '#ionic/storage';
import { Platform} from 'ionic-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '#angular/service-worker';
import { environment } from '../environments/environment';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
Platform,
HttpClientModule,
FormsModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production
})
],
declarations: [AppComponent],
providers: [InAppBrowser, SplashScreen, StatusBar],
bootstrap: [AppComponent]
})
export class AppModule {}
login.ts (has the results i want to return)
import { Component } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Router } from '#angular/router';
import { UserData } from '../../providers/user-data/user-data';
import { UserOptions } from '../../interfaces/user-options';
#Component({
selector: 'page-login',
templateUrl: 'login.html',
styleUrls: ['./login.scss'],
})
export class LoginPage {
resposeData: any;
loginData: any = {};
allMedia:any =[];
mediaType:string = '';
offset: number = 0;
login: UserOptions = { username: '', password: '' };
submitted = false;
constructor(
public userData: UserData,
public router: Router,
)
{
this.allMediaSet();
}
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.subscribe(data => {
console.log(data);
});
}
onLogin(form: NgForm) {
this.submitted = true;
if (form.valid) {
this.userData.login(this.login.username);
this.router.navigateByUrl('/app/tabs/schedule');
}
}
}
any help?
Your question seems like not Ionic specific but it is about Angular. Since good old Ionic 3 / Angular 4 days, Angular moved on from Http to HttpClient.
Please see here: https://angular.io/guide/http#setup
You need to ensure you migrate your Angular code to use the latest HttpClientModule:
https://devops.datenkollektiv.de/migrating-from-angular-httpmodule-to-new-angular-43-httpclientmodule.html
In short:
replace 'Http' with 'HttpClient':
import {Http} from '#angular/http';
becomes
import { HttpClient } from '#angular/common/http';
Remove manual extraction of JSON via map operator:
this.userData.allMedias(this.offset).map(res => res.json())
becomes
this.userData.allMedias(this.offset)

Logout From website if user does not do any activity in our web from Last 15 minutes

how to Logout From website if user does not do any move in our web from 15 minutes?
In Your angular app
npm install --save #ng-idle/core #ng-idle/keepalive angular2-moment
Set up your application module
Open src/app/app.module.ts and import the Ng2IdleModule using
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { NgIdleKeepaliveModule } from '#ng-idle/keepalive'; // this includes the core NgIdleModule but includes keepalive providers for easy wireup
import { MomentModule } from 'angular2-moment'; // optional, provides moment-style pipes for date formatting
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MomentModule,
NgIdleKeepaliveModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Extend your Main component
import { Component, OnInit } from '#angular/core';
import { Router, NavigationStart } from '#angular/router';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '#ng-idle/core';
import { Keepalive } from '#ng-idle/keepalive';
#Component({
selector: 'app-theme',
templateUrl: './theme.component.html',
styleUrls: ['./theme.component.css']
})
export class AppComponent implements OnInit {
lastPing?: Date = null;
constructor(private route: Router, private idle: Idle, private keepalive: Keepalive) {
idle.setIdle(5);
idle.setTimeout(900);
idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
idle.onIdleEnd.subscribe(() => { });
idle.onTimeout.subscribe(() => {
this.logout();
});
idle.onIdleStart.subscribe(() => {
});
idle.onTimeoutWarning.subscribe((countdown) => {
});
keepalive.interval(5);
keepalive.onPing.subscribe(() => this.lastPing = new Date());
this.reset();
}
ngOnInit() {
}
reset() {
this.idle.watch();
}
logout() {
//--
// LogoutCode
//---
}
}

Angular 8: not able to get message from Rest Api

I used following links https://grokonez.com/python/django-angular-6-example-django-rest-framework-mysql-crud-example-part-2-django-server and https://grokonez.com/frontend/django-angular-6-example-django-rest-framework-angular-crud-mysql-example-part-3-angular-client to create a django rest API and angular app that calls this rest.
Considering that I'm new in such kind of development so I created as a first step an App that just displays customers list.
Django rest API is fine working. I tested it with the browser:
But my problem is with the angular app, seems that it's not able to get message with the same URL: http://localhost:8000/customers
Below is my angular code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomersListComponent } from './customers-list/customers-list.component';
#NgModule({
declarations: [
AppComponent,
routingComponents,
CustomersListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { CustomersListComponent } from './customers-list/customers-list.component';
const routes: Routes = [
{ path: 'customers', component: CustomersListComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
customer.ts
export class Customer {
id: number;
name: string;
age: number;
active: boolean;
}
customer.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CustomerService {
private baseUrl = 'http://localhost:8000/customers';
constructor(private http: HttpClient) { }
getCustomersList(): Observable<any> {
return this.http.get(`${this.baseUrl}/`);
}
}
customers-list.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { Observable } from 'rxjs';
import { CustomerService } from '../customer.service';
import { Customer } from '../customer';
#Component({
selector: 'app-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.css']
})
export class CustomersListComponent implements OnInit {
customers: Observable<Customer[]>;
constructor(private customerService: CustomerService) { }
ngOnInit() {
console.log("Hellllllllo from customers-list.component.ts ngOnInit");
this.reloadData();
}
reloadData() {
this.customers= this.customerService.getCustomersList();
}
}
customers-list.component.html
<h1>Customers {{JSON.stringify(this.customers)}}</h1>
<div *ngFor="let customer of customers" style="width: 300px;">
<h2>Hello iii</h2>
<div>
<label>Name: </label> {{customer.name}}
</div>
<div>
<label>Age: </label> {{customer.age}}
</div>
<div>
<label>Active: </label> {{customer.active}}
</div>
</div>
The result that got when calling /customers from the browser is the following:
"Routing and Navigation" message is coming from app.component.html
As you can see message Customers is displayed but everything that corresponds to the variable customers (which is the list of customers) is not displayed.
Has someone an idea what's the main cause of this issue? and how I can fix it?
Thank you in advance
You should subscribe to get the response from the API because http.get returns an observable, observable invokes only when you subscribe to it. try the following method
reloadData() {
this.customerService.getCustomersList().subscribe((res: any) => {
this.customers = res;
});
}
In your service
getCustomersList(): Observable<any> {
return this.http.get(`${this.baseUrl}/`);
}
This function returns an observable
So you should subscribe to it like this to make the request
this.customerService.getCustomersList().subscribe((res: any) => {
this.customers = res;
});
Or in your html file you can add async pipe like this
*ngFor="let customer of customers | async

Trying to pass JSON data with angular/nativescript routing

I'm currently working on a nativescript/angular/typescript project and I'm basically trying to pass JSON data from one view (property) to another (propertyinfo).
First, I load up a JSON file in property.service.ts:
import { Injectable } from '#angular/core';
import { HttpClientModule, HttpClient } from '#angular/common/http';
#Injectable()
export class PropertyService {
public propertyData: any;
public selectedProperty: any;
constructor(private http: HttpClient) {
this.loadProperties();
}
loadProperties() {
this.http.get('/pages/property/property.json').subscribe(
(data) => {
this.propertyData = data;
}
)
}
}
This JSON data gets displayed in a view property.component.html:
<StackLayout *ngFor="let item of propertyData" class="list-group" xstyle="height: 300">
<GridLayout rows="110" columns="*, 40" (tap)="details(item)">
<StackLayout row="0" col="0">
<Label text="{{item.streetName}} {{item.houseNumber}}" class="text-primary p-l-30 p-t-5"></Label>
<Label text="{{item.etc}} {{item.etc}}" class="text-primary p-l-30 p-t-5"></Label>
</StackLayout>
<Label row="0" col="1" text="" class="fa arrow" verticalAlignment="middle"></Label>
</GridLayout>
<StackLayout class="hr-light"></StackLayout>
Here, the (tap)="details(item)" will call a function in property.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
import { PropertyService } from './property.service';
#Component({
selector: 'app-property',
templateUrl: 'pages/property/property.component.html',
providers: [PropertyService]
})
export class PropertyComponent implements OnInit {
public propertyData: any;
constructor(private router: Router, private propertyService: PropertyService) {}
ngOnInit() {
this.propertyData = this.propertyService.propertyData;
}
details(item: any) {
this.propertyService.selectedProperty = item;
this.router.navigate(["/propertyinfo"]);
}
}
Now, when I perform a console.log(JSON.stringify(this.propertyService.selectedProperty)); within my details function, the output is as follows:
JS: {"ID":4,"description":"Lorem ipsum dolor sit amet...", "streetName":"Somestreet","houseNumber":459,"etc":"etc"}
This is my propertyinfo.component.ts:
import { Component, OnInit } from '#angular/core';
import { PropertyService } from '../property/property.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-propertyinfo',
templateUrl: 'pages/propertyinfo/propertyinfo.component.html'
})
export class PropertyinfoComponent implements OnInit {
public selectedProperty: any;
constructor(private propertyService: PropertyService, private router: Router) {
this.selectedProperty = this.propertyService.selectedProperty;
}
ngOnInit() { }
}
Yet, when I perform a console.log(JSON.stringify(this.selectedProperty)); inside the constructor, the output is JS: undefined.
At the bottom of this post, I'll add the app.routing.ts and app.module.ts files so you can see all of my imports/directives etc. I'm really at a loss as to what I'm missing. I hope you can help me.
app.routing.ts:
import { NgModule } from "#angular/core";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { Routes } from "#angular/router";
import { PropertyComponent } from "./pages/property/property.component";
import { PropertyinfoComponent } from ".//pages/propertyinfo/propertyinfo.component";
const routes: Routes = [
{ path: "", component: PropertyComponent },
{ path: "propertyinfo", component: PropertyinfoComponent },
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
app.module.ts:
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptHttpClientModule } from "nativescript-angular/http-client";
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { AppRoutingModule } from "./app.routing";
import { AppComponent } from "./app.component";
import { PropertyService } from "./pages/property/property.service";
import { PropertyComponent } from "./pages/property/property.component";
import { PropertyinfoComponent } from "./pages/propertyinfo/propertyinfo.component";
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptRouterModule,
HttpClientModule,
NativeScriptHttpClientModule,
],
declarations: [
AppComponent,
PropertyComponent,
PropertyinfoComponent
],
providers: [
PropertyService
],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class AppModule { }
Thank you for any help in advance. If I need to clear things up/provide any more info, please let me know.
console.log(JSON.stringify(this.selectedProperty)) returns undefined in PropertyinfoComponent because the PropertyService service being injected is not the same instance in PropertyinfoComponent than it is in PropertyComponent
you did not post the full .html for both component so I can only assume that you have something like the PropertyComponent is a parent component and has a reference/include a PropertyinfoComponent in the html and because of the way angular work, it injected a new instance of the service instead of using the one from the parent component.
check Thierry Templier answer for more information about angular service injection for this type of issue : How do I create a singleton service in Angular 2?

Ionic 2 rootPage not showing

I'm new to Ionic and just started a new project. I picked the template with the 3 tabs at the bottom but now I want a new startpage.
I created a page called LoginPage but when I try to swap TabsPage for LoginPage it just shows an empty screen.
Here are the files
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { LoginPage } from '../pages/login/login';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = LoginPage;
constructor(platform: Platform) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
login.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
constructor(public navCtrl: NavController) {
}
}
app.module.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { SettingsPage } from '../pages/settings/settings';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import {LoginPage} from "../pages/login/login";
#NgModule({
declarations: [
MyApp,
SettingsPage,
ContactPage,
HomePage,
TabsPage,
LoginPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
SettingsPage,
ContactPage,
HomePage,
TabsPage,
LoginPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
If there are other files you need to see, just say so and I will add them.
Thanks in adventage.
Try adding the login page using ionic CLI
$ ionic g page login
Then add the page in app.module.ts and edit app.component.ts like you mentioned
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { LoginPage } from '../pages/login/login';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = LoginPage;
constructor(platform: Platform) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}