How to redirect to main component after success login - angular2-routing

I am a new in Angular2 and stacked on next step. My web site starts with a login page. I enter user and password( Login Component), receive from backend success response and want to redirect to the main page ( Main Component).
My project structure is:
here
login.component.ts
import { Component, OnInit, style } from '#angular/core';
import 'rxjs/add/operator/map';
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { URLSearchParams } from '#angular/http';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import $ from 'jquery';
import { parse } from 'url';
import { FormControl, FormGroup } from "#angular/forms";
import { LoginServiceService } from './login.service';
import 'rxjs/add/operator/map';
import { users } from './login.users';
import {Router} from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
public data;
constructor(public jsonLoginDataService: LoginServiceService) {
}
ngOnInit() {
}
login(userName, password) {
let user = new users(userName, password);
this.jsonLoginDataService.checkLogin(user).subscribe(
function (success) {
this.data = success;
//this.datahandle(success);
if(this.data.length==0)
{
console.log("User wasn't found");
}
else
{
//Redirect to Main Component
}
},
error => console.log('Getting Server Data Error :: ' +
JSON.stringify(error)));
}
datahandle(jsonData) {
let keys = Object.keys(jsonData);
}
}
login.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { CommonModule } from '#angular/common';
import { TagCloudModule } from 'angular-tag-cloud-module';
import { LoginComponent } from './login.component';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import {MatDialogModule} from '#angular/material/dialog';
import { LoginServiceService } from './login.service';
import { RouterModule, Routes } from '#angular/router';
import { MainComponent } from '../main/main.component';
import { routing } from './login.routing';
#NgModule({
declarations: [
LoginComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
TagCloudModule,
NgbModule,
MatDialogModule
],
providers: [LoginServiceService],
bootstrap: [LoginComponent]
})
export class LoginModule { }
main.component.ts
import { Component, OnInit, style } from '#angular/core';
import 'rxjs/add/operator/map';
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { CcDataServiceService } from './api.service';
import { new_Item } from './main.newItem';
import { URLSearchParams } from '#angular/http';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import $ from 'jquery';
import { new_Income } from './main.newIncome';
import { parse } from 'url';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
#Injectable()
export class MainComponent implements OnInit {
public exp_total_amount: number;
add_category: string;
add_ex_budget: string;
add_income_category: string;
add_income_amount: number;
public real_total_amount: number;
public pass_new_month_amount: number;
public total_income: number;
public current_budget: number;
real_amount: number;
temp_amount: number;
service: string;
service1: string;
expected_amount: number;
deviation: number;
left_amount: number;
history: string;
income_amount: number;
purchase_date: string;
public data;
public data_Income;
public real_data;
public saving_progress: number;
public balance_progress: number;
public left_spend_amount: number;
constructor(public jsonDataService: CcDataServiceService) {
}
ngOnInit() {
this.loadData();
}
datahandle(jsonData) {
//console.log('check your data' + JSON.stringify(jsonData)); //<-----check data
// may parse your data
let keys = Object.keys(jsonData);
}
updateDeviation() {
for (let i = 0; i < this.data.length; i++) {
this.data[i].deviation = Math.round((this.data[i].real_amount * 100) / (this.data[i].expected_amount) * 10) / 10;
}
}
updateTotals() {
this.exp_total_amount = 0;
this.real_total_amount = 0;
for (let i = 0; i < this.data.length; i++) {
this.exp_total_amount += Math.round((this.data[i].expected_amount) * 10) / 10;
this.real_total_amount += Math.round((this.data[i].real_amount) * 10) / 10;
this.data[i].left_amount = Math.round((this.data[i].expected_amount - this.data[i].real_amount) * 10) / 10;
}
this.pass_new_month_amount = Math.round((this.exp_total_amount - this.real_total_amount) * 10) / 10;
//this.
this.checkAmount();
}
updateCurrentBadget() {
this.current_budget = Math.round(this.total_income - this.real_total_amount) * 10 / 10;
this.saving_progress = Math.round(this.current_budget * 100 / this.total_income) * 10 / 10;
this.balance_progress = Math.round(this.pass_new_month_amount * 100 / this.exp_total_amount) * 10 / 10;
this.checkAmount();
}
updateIncome() {
this.total_income = 0;
for (let i = 0; i < this.data_Income.length; i++) {
this.total_income += Math.round((this.data_Income[i].income_amount) * 10) / 10;
}
this.checkAmount();
}
reloadPageData() {
this.loadData();
this.updateIncome();
this.checkAmount();
this.ngOnInit();
}
addCategory(add_category, add_ex_budget) {
let new_item = new new_Item(add_category, add_ex_budget);
this.jsonDataService.setCategory(new_item).subscribe(
function (success) {
this.data = success;
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
this.updateTotals();
this.reloadPageData();
this.updateCurrentBadget();
this.checkAmount();
}
addIncomeCategory(add_income_category, add_income_amount) {
let new_income = new new_Income(add_income_category, add_income_amount);
this.jsonDataService.setIncomeData(new_income).subscribe(
function (success) {
this.data = success;
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
this.updateIncome();
this.reloadPageData();
this.clearFields();
this.checkAmount();
}
deleteCategory(service1) {
this.jsonDataService.deleteCategory(service1).subscribe(
function (success) {
this.data = success;
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
this.updateTotals();
this.reloadPageData();
}
updateBudget(this) {
let updatedData;
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].service === this.service) {
this.data[i].real_amount = +this.data[i].real_amount;
this.data[i].real_amount += this.temp_amount;
this.data[i].history += " $" + this.temp_amount + " - " + this.purchase_date + ";";
updatedData = this.data[i];
}
}
this.jsonDataService.performPayment(updatedData).subscribe(
function (success) {
this.data = success;
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
this.updateDeviation();
this.updateTotals();
this.updateCurrentBadget();
this.clearFields();
this.loadData();
}
hideLog() {
if ($('#input_log').val() === "Show log") {
$('#log_table').css('display', 'block');
$('#input_log').val('Hide log');
}
else if ($('#input_log').val() === "Hide log") {
$('#log_table').css('display', 'none');
$('#input_log').val('Show log');
}
}
clearFields() {
$('input').each(function () {
if (($(this).attr('type') == 'number') || ($(this).attr('type') == 'text'))
$(this).val('');
});
}
checkAmount() {
let xx = (this);
$('#budget_table tbody tr').each(function () {
let y = parseInt($(this).children('td:eq(3)').text());
if (y < 0) {
$(this).children('td:eq(3)').css('color', "red ");
}
if (y > 0) {
$(this).children('td:eq(3)').css('color', "green ");
}
});
$('label').each(function () {
let x = parseInt((this).innerHTML);
if (xx.real_total_amount > xx.exp_total_amount) {
if (x == xx.real_total_amount) {
$(this).css('color', "red ");
}
}
if (xx.real_total_amount < xx.exp_total_amount) {
if (x == xx.real_total_amount) {
$(this).css('color', "green ");
}
}
if ((x == xx.pass_new_month_amount) && (xx.pass_new_month_amount < 0)) {
$(this).css('color', "red ");
}
if ((x == xx.pass_new_month_amount) && (xx.pass_new_month_amount > 0)) {
$(this).css('color', "green ");
}
});
// Progress bar coloured
$('.progress-bar').each(function () {
let width_size = $(this).prop('style')['width'];
let new_width = width_size.replace('%', '');
if (new_width > 100) {
$(this).css('background-color', 'red');
}
});
}
loadData() {
let thisx = this;
let thisi = this;
this.jsonDataService.view_services(thisx).subscribe(
function (success) {
thisx.data = success;
thisx.datahandle(success);
thisx.updateDeviation();
thisx.updateTotals();
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
this.jsonDataService.view_income(thisi).subscribe(
function (success) {
thisi.data_Income = success;
thisi.updateIncome();
thisi.updateCurrentBadget();
},
error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));
}
}
main.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { CommonModule } from '#angular/common';
import { TagCloudModule } from 'angular-tag-cloud-module';
import { MainComponent } from './main.component';
import { CcDataServiceService } from './api.service';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import {MatDialogModule} from '#angular/material/dialog';
// Import HttpClientModule from #angular/common/http
//import {HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
MainComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
TagCloudModule,
NgbModule,
MatDialogModule,
],
providers: [CcDataServiceService],
bootstrap: [MainComponent]
})
export class MainModule { }
What I have to do for redirect to MainComponent?
Regards.

Create the Following for Manage Navigation and Routing
app.routing.ts
import {ModuleWithProviders} from '#angular/core'
import {RouterModule,Routes} from '#angular/router'
import {LoginComponent} from './login/login.component.ts'
import {MainPageComponent} from './main/main.component'
export const routes:Routes=[
{
path:'',
redirectTo:'login',
pathMatch:'full'
},
{
path:'login',
component:LoginComponent
},
{
path:'main',
component:MainPageComponent
}
]
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
app.module.ts
import { routing } from './app.routes';
#NgModule({
imports: [
routing
]
})
login.component.ts
import {Router} from '#angular/router'
constructor(public router:Router) { }
navigate(){
this.router.navigate(['\main']); //Add this line to navigate in your method
}
Add this line to where you want to place your navigation
app.component.html
<router-outlet></router-outlet>
I hope this help and easy to understand..
learn routing visit this site
https://coryrylan.com/blog/introduction-to-angular-routing

Related

Fetch data from asp.net into highchart

I'm trying to make an application with highchart and asp.net and I followed several tutorials and applications because it's a new thing for me.
But I don't know how to fetch data from asp.net into highcharts.js. I tried to do a getChartData function following one video and then I realised that is for chart.js.Can you give me a idea?
This is my code:
bar-chart.ts
import { Component, OnInit } from '#angular/core';
import * as Highcharts from 'highcharts';
import { SalesDataService } from '../../services/sales-data.service';
import * as moment from 'moment';
#Component({
selector: 'app-bar-chart',
templateUrl: './bar-chart.component.html',
styleUrls: ['./bar-chart.component.css']
})
export class BarChartComponent implements OnInit {
constructor(private _salesDataServices:SalesDataService ){}
orders:any;
orderLabels:string[];
orderData:number[];
public barChartLabels:string[];
public barChartData:any[];
title = 'myHighChartsApp';
highcharts = Highcharts;
public options: any ={
chart : {
type: "column"
},
title: {
text: "Monthly Sales Chart Department Wise"
},
xAxis:{
},
yAxis: {
title:{
text:"Sales in Million $"
}
},
series: []
}
ngOnInit() {
}
getChartData(res:Response){
this.orders=res['page']['data'];
const data=this.orders.map(o =>o.total);
const formattedOrders=this.orders.reduce((r,e) => {
r.push([moment(e.placed).format('YY-MM-DD'),e.total]);
return r;
},[]);
const p=[];
console.log('formattedOrders:',formattedOrders);
const chartData=formattedOrders.reduce((r,e)=>{
const key=e[0];
if(!p[key]){
p[key]=e;
r.push(p[key]);
}else {
p[key][1]+=e[1];
}
return r;
},[]);
return chartData;
}
}
sales-data-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs';
import { Order } from '../shared/order';
#Injectable({
providedIn:'root'
})
export class SalesDataService {
constructor(private _http: Http) { }
getOrders( pageIndex: number, pageSize: number
) {
return this._http.get('http://localhost:5103/api/order/'+ pageIndex + '/' + pageSize
)
.map(res => res.json());
}
}

IONIC 4 - The event ionViewWillEnter only fires once

Please, I am building a Sidemenu Ionic app with firebase firestore, when it opens, the app shows my collections and data, but when browsing between pages with sidemenu and returning to the data page, there is no data return nothing, I need to refresh a browser page to see the data again. I already checked the life cycle and the ionViewWillEnter the event only fires once.
import { Component, OnInit } from '#angular/core';
import { Evento, EventoService} from 'src/app/services/evento.service';
import { Router, RouterEvent } from '#angular/router';
import { LoadingController, NavController } from '#ionic/angular';
#Component({
selector: 'app-eventos',
templateUrl: './eventos.page.html',
styleUrls: ['./eventos.page.scss'],
})
export class EventosPage{
eventos: Evento[];
pages = [
{
url: '/menu/eventos',
}
];
selectedPath = '';
constructor(private eventoService: EventoService, private router: Router,
private loadingController: LoadingController, private navCtrl: NavController) {
this.navCtrl.setDirection('root');
}
ionViewWillEnter(){
console.log(' Teste 3: ionViewWillEnter ')
this.eventoService.getAllEventos().subscribe(res => {
this.eventos = res;
let dateString = 'item.data';
let newDate = new Date(dateString);
this.loadEvento();
});
}
async loadEvento() {
const loading = await this.loadingController.create({
message: 'Carregando eventos...',
spinner: 'crescent',
duration: 300
});
return await loading.present();
}
}
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Eventos</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-card class="card" *ngFor="let item of eventos" lines="inset" button [routerLink]="['/detailsEvento', item.id]"
routerdirection="forward">
<ion-card-header>
<ion-card-title class="texto"> {{item.nome}}</ion-card-title>
<ion-card-title class="texto"> Data: {{item.data | date:'dd/MM/yyyy'}}</ion-card-title>
</ion-card-header>
</ion-card>
</ion-content>
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { IonicModule } from '#ionic/angular';
import { EventosPage } from './eventos.page';
import { FontAwesomeModule } from '#fortawesome/angular-fontawesome';
const routes: Routes = [
{
path: '',
component: EventosPage
}
];
#NgModule({
imports: [
FontAwesomeModule,
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes)
],
declarations: [EventosPage]
})
export class EventosPageModule {}
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Evento {
nome: string;
data: string;
horario: string;
local: string;
descricao: string;
}
#Injectable({
providedIn: 'root'
})
export class EventoService {
private eventosCollection: AngularFirestoreCollection<Evento>;
private eventos: Observable<Evento[]>;
constructor(db: AngularFirestore) {
this.eventosCollection = db.collection<Evento>('eventos', ref => ref.orderBy('data'));
this.eventos = this.eventosCollection.snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return{ id, ...data };
});
})
);
}
getAllEventos(){
return this.eventos;
}
getEvento(id){
return this.eventosCollection.doc<Evento>(id).valueChanges();
}
}
constructor(
private afStore: AngularFirestore,
private router: Router,
) {
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd && this.router.url === '/main-screen/home')
{
this.storage.get('userInfo').then((val) => {
if (val) {
// console.log(val);
this.profesion = val.Profesion ? val.Profesion : 'popular';
if ( this.profesion === 'popular') {
this.allCollectionVideo();
} else {
this.getDefaultProfesion(this.profesion);
}
}
});
}
});
}
It can resolve your issue.

Angular 6, Firebase Storage web Image gallery

I've got a problem with downloading URL during uploading an image file.
I want to use this url to show this images from Firebase storage.
Uplad is working, because i can see this photos on my storage on firebase, but i can't download it and show in my web
Here's a upload.service.ts
import { Injectable } from '#angular/core';
import { AngularFireModule } from 'angularfire2';
import { GalleryImage } from '../models/galleryImage.model';
import { AngularFireDatabase} from 'angularfire2/database';
import { FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
import { Upload } from '../models/upload.model';
import * as firebase from 'firebase';
#Injectable()
export class UploadService {
private basePath = '/uploads';
private uploads: FirebaseListObservable<GalleryImage[]>;
constructor(private ngFire: AngularFireModule, public db: AngularFireDatabase) { }
uploadFile(upload: Upload) {
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`${this.basePath}/${upload.file.name}`)
.put(upload.file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
// three observers
// 1.) state_changed observer
(snapshot) => {
// upload in progress
upload.progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
console.log(upload.progress);
},
// 2.) error observer
(error) => {
// upload failed
console.log(error);
},
// 3.) success observer
(): any => {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
upload.url = downloadURL;
console.log('FirstURL', downloadURL);
console.log('SecondURL', upload.url);
this.saveFileData(upload);
});
}
);
}
private saveFileData(upload: Upload) {
this.db.list(`${this.basePath}/`).push(upload);
console.log('File saved at' + upload.url);
}
}
Here's my image.service.ts
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { FirebaseApp } from 'angularfire2';
import 'firebase/storage';
import { GalleryImage } from '../models/galleryImage.model';
import * as firebase from 'firebase';
#Injectable()
export class ImageService {
private uid: string;
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
this.afAuth.authState.subscribe(auth => {
if (auth !== undefined && auth !== null) {
this.uid = auth.uid;
}
});
}
getImages(): Observable<GalleryImage[]> {
return this.db.list('uploads').valueChanges();
}
getImage(key: string) {
return firebase.database().ref('uploads/' + key).once('value')
.then((snap) => snap.val());
}
}
Here's my upload.model.ts
export class Upload {
$key: string;
file: File;
url: string;
progress: number;
createdOn: Date = new Date();
name: string;
constructor(file: File) {
this.file = file;
}
}

angular 5, http.get is ok but http.patch with same parameters returns 404 NOT FOUND

I work with Angular 5.
I use a json for data.
I use very often http.get and it always works fine.
But http.patch returns an ERROR 404 NOT FOUND !
Does anybody can explain to me why ?
My config:
Angular CLI: 1.5.0
Node: 6.11.3
OS: win32 x64
Angular: 5.0.0
import { Component, OnInit } from '#angular/core';
import { Constants } from '../shared/classes/constantes/fr/constants';
import { HttpClientModule } from '#angular/common/http';
import { HttpClient } from '#angular/common/http';
import { HttpParams } from '#angular/common/http';
import { Response } from '#angular/http';
#Component({
selector: 'app--test',
templateUrl: './-test.component.html',
styleUrls: ['./-test.component.scss']
})
export class TestComponent implements OnInit {
id: number;
latitude: number;
longitude: number;
constructor(
private http: HttpClient
) {}
ngOnInit() {
this.id = 3;
this.latitude = 44.7637;
this.longitude = -0.5536;
const body = {
'latitude': this.latitude,
'longitude': this.longitude
};
this.http.get(Constants.USERS_URL + '?id=' + this.id).subscribe(data => {
const userLogged = data;
if (!userLogged[0]) {
// NEVER HAPPENS : IT'S OK
} else {
this.http.patch(Constants.USERS_URL + '?id=' + this.id, body).subscribe();
});
}
}

ERROR in ./src/app/app.module.ts Module not found

I'm working on angular-cli. I got following errors.
ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '#angular/router/src/router_module' in
'E:\xampp\Angular-cli\Login\src\app'
# ./src/app/app.module.ts 13:0-69
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
I've this library #angular/router/src/router_module in my node_module. What is missing?
Here are required files.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AdminAccount } from './admin/admin.component';
import { LoginForm } from './login/login.component';
import { FileData } from './filedata/filedata.component';
import { ROUTER_PROVIDERS } from "#angular/router/src/router_module";
import { RouterModule, Routes, ROUTES } from "#angular/router";
import { Http, Response } from "#angular/http";
import { Route } from './router/router.component';
#NgModule(
{
imports: [RouterModule ,Route, BrowserModule, Http, Response, AdminAccount, LoginForm, FileData, Route],
declarations: [AppComponent],
providers: [ROUTER_PROVIDERS],
bootstrap: [AppComponent]
})
export class AppModule { }
router.component.ts
import { Component, OnInit } from '#angular/core';
import { RouterModule } from "#angular/router";
import { LoginForm } from "../login/login.component";
import { AdminAccount } from "../admin/admin.component";
export const Route = RouterModule.forRoot(
[
{ path: '/', component: LoginForm },
{ path: '/admin', component: AdminAccount }
]);
app.component.ts
import { Component } from "#angular/core";
import { LoginForm } from "./login/login.component";
import { AdminAccount } from "./admin/admin.component";
import { Routes, RouterModule } from "#angular/router";
import { FileData } from "./filedata/filedata.component";
#Component(
{
selector: "root",
templateUrl: "./app.component.html",
})
export class AppComponent {}
If need more file let me know.
#Fahad Nasir Here's AdminAcount.
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
#Component(
{
selector: "admin",
templateUrl: "./admin.component.html",
})
export class AdminAccount
{
adminUser = document.cookie.split("??")[0];
adminPass = document.cookie.split("??")[1];
constructor(public router: Router)
{
if (document.cookie !== undefined)
{
if (this.adminUser == "admin" && this.adminPass == "admin")
{
console.log("Welcome!");
}
else
{
this.router.navigate(["Loginform"]);
console.log("Redirect!");
}
}
else
{
console.log("Error: Undefined Login!");
}
}
}
Here Have a look

Resources