Angular prefilled form data becomes null when submitting - angular8

I have created an Angular form to update the user details. The fields values of the form are filled by the user details fetched from the backend when the form loads. If the user wishes to update any field they can update and submit the form. But the field values of the fields which user didn't change are set as null even though those fields are initialized at the beginning. Can someone please explain how to get the prefilled unchanged field values when submitting the form?
The HTML file is this,
<app-navbar></app-navbar>
<div class="container">
<form [formGroup]="profileForm" style="margin-top: 60px;" disabled="true" (ngSubmit)="onSubmit()">
<input type="file" id="file" (change)="onFileSelected($event)" accept="image\jpeg" formControlName="profPic">
<div class="row">
<!--Profile Picture-->
<div class="col-12 col-md-4 d-flex justify-content-center">
<label for="file">
<a (mouseenter)="hoverIdx = 1"
(mouseleave)="hoverIdx = -1"
id="overlay">
<span [ngClass]="{ 'overlay-icon': true, 'hide': hoverIdx !== 1 }"
class="rounded-circle">
<fa-icon [icon]="cameraIcon" class="icon"></fa-icon>
</span>
<img
[src]="profPic"
class="rounded-circle"
width="300"
height="300"
/>
</a>
</label>
<div class="col-md-2 align-self-end ml-auto p-2" id="deleteIcon">
<fa-icon [icon]="deleteIcon"></fa-icon>
</div>
</div>
<div class="col-12 col-md-8">
<div class="card" style="margin-bottom: 20px;">
<div class="card-body" >
<!---Intro-->
<div class="row" style="font-size: 60px;">
<div class="col-12">Hi, {{ fNme }}</div>
</div>
<!--first name & last name-->
<div class="row" style="margin-top: 10px;">
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="fName"
matInput placeholder="First Name"
[value]="fNme"
(change)="fNmeChnge = true"/>
</mat-form-field>
</div>
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="lName"
matInput placeholder="Last Name"
[value]="lNme"
(change)="lNmeChnge = true" />
</mat-form-field>
</div>
</div>
<!--row-->
<!-- email & country-->
<div class="row" style="margin-bottom: 25px;">
<div class="col-12 col-md-6">
<mat-form-field appearance="outline">
<input formControlName="email"
matInput placeholder="Email"
[value]="email"
(change)="emailChnge = true"/>
</mat-form-field>
</div>
<div class="col-12 col-md-6">
<mat-form-field appearance="outline" >
<input formControlName="country"
matInput placeholder="Country"
[value]="country"
(change)="countryChnge = true"/>
</mat-form-field>
</div>
</div>
<!--row-->
</div>
</div>
<button type="button" class="btn btn-primary float-right" style="margin-left:10px" type="submit">Save</button>
<button type="button" class="btn btn-outline-primary float-right" (click)="cancel()">Cancel</button>
</div><!--col-md-8-->
</div><!--row-->
</form>
</div><!--container-->
The component file is this,
import { User } from './../shared/user.model';
import { F_NAME, L_NAME, AUTHENTICATED_USER, PROF_PIC, BASE64URL } from './../../app.constants';
import { Component, OnInit, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthenticationService } from '../service/authentication.service';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '#angular/material/dialog';
import { DialogOverviewExampleDialog } from './dialog';
import { faCamera, faTrashAlt } from '#fortawesome/free-solid-svg-icons';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: User;
cameraIcon = faCamera;
deleteIcon = faTrashAlt;
profPic: any;
profileForm: FormGroup;
email: string;
fNme: string;
lNme: string;
country: any;
selectedFile: File = null;
base64Data: any;
fNmeChnge: any;
lNmeChnge: any;
countryChnge: any;
emailChnge: any;
title = 'Profile';
constructor(
private service: AuthenticationService,
public dialog: MatDialog,
private sanitizer: DomSanitizer
) {
}
ngOnInit() {
this.email = sessionStorage.getItem(AUTHENTICATED_USER);
this.profileForm = new FormGroup({
fName: new FormControl(null, [Validators.required]),
lName: new FormControl(null, Validators.required),
email: new FormControl(null, [Validators.required, Validators.email]),
country: new FormControl(null, Validators.required)
});
this.service.getUser(this.email)
.subscribe(res => {
this.fNme = res.fNme;
this.lNme = res.lNme;
this.country = res.country;
this.profPic = BASE64URL + res.profPic ;
});
}
openDialog(): void {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '500px'
});
}
onFileSelected(event){
this.selectedFile = event.target.files[0] as File;
const reader = new FileReader();
reader.onload = e => this.profPic = reader.result;
reader.readAsDataURL(this.selectedFile);
}
onSubmit() {
const fd = new FormData();
fd.append('file', this.selectedFile);
this.service.uploadImage(fd, this.email);
this.user = new User(this.profileForm.get('fName').value,
this.profileForm.get('lName').value,
this.profileForm.get('country').value,
this.profileForm.get('email').value);
console.log(this.user);
this.service.updateProfile(this.user, this.email);
// .subscribe(res => {
// this.fNme = res.fNme;
// this.lNme = res.lNme;
// this.country = res.country;
// this.profPic = BASE64URL + res.profPic ;
// });
this.ngOnInit();
}
I gets the user data from the server via these codes,
uploadImage(file: FormData, email: string) {
this.http.put<any>(`${API_URL}/profile-picture/${email}`, file)
.subscribe(res => {console.log(res); });
}
updateProfile(user: User, email: string) {
this.http.put<any>(`${API_URL}/profile/${email}`, user).subscribe();
}
getUser(email: string) {
return this.http.get<any>(`${API_URL}/user/${email}`);
}

Related

upload file array formData vue

how to make a file upload function in vue js ? here I create a dynamic form that can be added.
I made a form name and uploaded a file
when the add Attachment button is clicked, the form increases
when I send to the backend, only 1 file is sent, how to make the uploaded file into an array?
and this my code
<div class="col-6">
<div class="row row g-3" v-for="(attachment, index) in attachment" :key="index">
<div style="font-size:13px">Attachment</div>
<div class="col-sm-4">
<input type="text" v-model="attachment.att_name">
</div>
<div class="col-sm-7">
<div class="col">
<input type="file" id="file" ref="file" #change="selectFile"/>
</div>
</div>
</div>
<div style="margin-top: 15px;">
<button type="button" #click="addNewAttachment">Add Attachment</button>
</div>
</div>
//submit button
<div style="margin-top:50px">
<button type="button" #click="onsubmit">Submit</button>
</div>
and this
export default {
name : 'bbb',
data() {
return {
attachment : [
{
att_name: '',
att_file:'',
}
],
}
},
methods:{
selectFile(e) {
const selectedFile = e.target.files[0];
this.attachment.att_file = selectedFile;
},
addNewAttachment() {
this.attachment.push(
{
att_name: '',
att_file:'',
}
);
},
onsubmit(){
const data = new FormData();
data.append("item[]", JSON.stringify(this.attachment));
//for (var lop of data.entries()) {
//console.log(lop[1])
//}
}
}
}

I am unable to pass my v-model data to my backend for radio button type in vue.js ,How to pass that checked radio button value to my backend ??

I developed one page which is responsible for Registering the users previously i submitted the form without radio buttons, now i need to add radio buttons based on checked type button that value should be sent to the backend ,i am unable to figure out where did i mistaken please help me to fix this issue
Register.vue
<template>
<div class="main">
<div v-if="flag==true" class="container">
<img id="side-img" src="../assets/sideImg.png" alt="notFound" />
<p id="side-content">Online Book Shopping</p>
<div class="box">
<div class="headings">
<h5 class="signin" v-on:click="flip();" id="login" :class="{ active: isLogin }" #click="isLogin = true">Login</h5>
<h5 class="signup" id="signup" :class="{ active: !isLogin }" #click="isLogin = false">signup</h5>
</div>
<form ref="myForm" #submit.prevent="handlesubmit">
<div class="fullname">
<p>FullName</p>
<input type="name" id="name-input" class="namebox" required v-model="fullName" autocomplete="off" pattern="[A-Za-z]{3,12}">
</div>
<div class="username">
<p>EmailID</p>
<input type="email" id="Email-input" class="emailbox" autocomplete="off" required v-model="email" pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="password-section">
<p>Password</p>
<input :type="password_type" class="password" :class="{'password-visible': isPasswordVisible }" id="passField" v-model="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,}$" required>
<i class="bi bi-eye-slash" id="togglePassword" #click="togglePassword();"></i>
</div>
<div class="mobile">
<p>MobileNumber</p>
<input type="tel" class="telephone" autocomplete="off" v-model="mobile" id="tel" pattern="^\d{10}$" required>
</div>
<div class="role-btns">
<input type="radio" id="user" value="user" name="role" v-model="roleUser" >
<label for="user" class="radio-label">user</label>
<input type="radio" id="admin" value="admin" name="role" v-model="roleUser">
<label for="admin">admin</label>
</div>
<button class="btn-section" id="btn" type="submit">Signup</button>
</form>
</div>
</div>
<Login v-if="flag==false" />
</div>
</template>
<script>
import service from '../service/User'
export default {
name: 'Register',
components: {
Login: () => import('./Login.vue')
},
data() {
return {
fullName: '',
email: '',
password: '',
mobile: '',
roleUser:'',
password_type: "password",
isLogin: false,
isPasswordVisible: false,
flag: true,
title: 'Online Book Shopping'
}
},
methods: {
flip() {
this.flag = !this.flag;
},
togglePassword() {
this.password_type = this.password_type === 'password' ? 'text' : 'password'
this.isPasswordVisible = !this.isPasswordVisible
},
handlesubmit() {
let userData = {
fullName: this.fullName,
email: this.email,
password: this.password,
mobile: this.mobile
}
service.userRegister(userData).then(response => {
if (response.status == 201) {
alert("user registered successfully");
this.$refs.myForm.reset();
this.$router.push('/login');
}
return response;
}).catch(error => {
alert("invalid credentials");
return error;
})
}
}
}
</script>
<style lang="scss" scoped>
#import "#/styles/Register.scss";
</style>
let userData = {
fullName: this.fullName,
email: this.email,
password: this.password,
mobile: this.mobile,
roleUser:this.roleUser
}

How to show success message in vue js after inserting the date into database

I have a perfectly working form I can insert data into database using axios after form validation. I am just struggling to show a success message after inserting the data into the database. how to hide the form and display a succcess message in the same section after sending the data into the database??
here's my perfectly working code
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<div>
<form #submit.prevent="submit">
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx number">TRX No</label>
<input
type="text"
name="trx Number"
v-model="newUser.trx"
class="form-control trx-address-nooverflow"
placeholder="Copy paste your TRX no"
/>
<b-form-text id="input-formatter-help">
<a class="text-success">Your TRX address: {{trxNo}}</a>
</b-form-text>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
type="text"
name="name"
v-model="newUser.name"
class="form-control"
placeholder="Enter you name"
/>
</div>
<div class="form-group col-md-3">
<label for="email">Email</label>
<input
type="text"
name="email"
v-model="newUser.email"
class="form-control"
placeholder="Enter valid email address"
/>
</div>
<div class="form-group col-md-3">
<label for="country">Country</label>
<country-select
id="Country"
v-model="newUser.country"
:country="newUser.country"
topCountry="US"
class="form-control"
/>
</div>
<div class="form-group col-md-3">
<label for="mobile">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="newUser.mobile_no"
type="text"
placeholder="Enter your mobile no."
/>
<b-form-text id="input-formatter-help">
Please enter valid phone number
</b-form-text>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
</div>
</div>
</div>
</form>
</div>
</div>
</b-container>
</template>
here's my vue js code
<script>
import axios from 'axios'
export default{
data(){
return{
errorMessage: "",
successMessage: "",
text: "success",
errors: [],
users: [],
newUser: {trx: "", name: "", country: "", email: "", mobile_no: ""}
}
},
computed: {
trxNo: function() {
return this.$store.state.myAddress;
}
},
mounted: function(){
this.getAllUsers();
},
methods:{
getAllUsers: function(){
axios.get('https://onex.tronpayer.com/api/update-info-form.php?action=read', { crossdomain: true })
.then((response) => {
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.users = response.data.users;
}
});
},
submit(){
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('https://onex.tronpayer.com/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx: "", name: "", country: "", email: "", mobile_no: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
}
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
if (!this.newUser.trx) {
this.errors.push("Trx Number Required.");
}
if (!this.newUser.name) {
this.errors.push("Name Required.");
}
if (!this.newUser.country) {
this.errors.push("Country Required.");
}
if (!this.newUser.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.newUser.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.newUser.mobile_no) {
this.errors.push("Mobile Number Required.");
}
if (!this.errors.length) {
return true;
}
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
You can use the v-if conditional rendering for disabling the form and showing the message.
https://v2.vuejs.org/v2/guide/conditional.html
Just create a variable like savingSuccessful: false and set it to true when your ajax request was successful.
Use it now in your form like
<form #submit.prevent="submit" v-if="!savingSuccessful">
This means your form will be displayed until your variable is true.
For a success-message you can create something like this:
<div class="success" v-if="savingSuccessful">
{{ this.text }}
</div>
Your message will be rendered when the variable is true.
Here a JSFiddle:
https://jsfiddle.net/MichelleFuchs/nydruxzw/2/

Aurelia custom element access data from child to parent view model

I am new to Aurelia and need help accessing values from custom element in another view.
I have a scenario where I would like to share input file for attachment in multiple forms. One of the approach I am taking is to create custom element for input files that can be shared with multiple forms in web application.
Below is my code:
Custom element called FilePicker which will be shared between multiple forms. In my Request paged I inserted the custom element called:
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
My requirement is to access property called validFiles which is an array. I would like to use values from validFiles to custom object in Request view model called formData['attachment']
TS:
import { customElement, useView, bindable, bindingMode } from 'aurelia-framework';
#customElement('file-picker')
#useView('./file-picker.html')
export class FilePicker {
#bindable accept = '';
#bindable multiple = false;
#bindable({ defaultBindingMode: bindingMode.twoWay }) files: FileList;
validFiles = [];
input: HTMLInputElement;
// Validate function for on change event to input file.
public filesChanged() {
if (!this.files) {
this.clearSelection();
}
if (this.files) {
this.processFiles();
}
}
// Trigger on button click
public triggerInputClick() {
this.input.click();
}
// Find value in array of object
private findValinArrObj(arr, key, val) {
return arr.map(function (v) { return v[key] }).indexOf(val);
}
// Process file for each new files uploaded via browser
private processFiles() {
if (this.files) {
for (let i = 0; i < this.files.length; i++) {
let findFile = this.findValinArrObj(this.validFiles, 'name', this.files.item(i).name);
if (findFile === -1) {
this.validFiles.push(this.files.item(i));
}
}
this.clearSelection();
}
}
// Remove file from fileNames and validFiles array
public removeByFileName(fileName) {
if (this.validFiles) {
for (let i = 0; i < this.validFiles.length; i++) {
if (this.validFiles[i].name === fileName) {
this.validFiles.splice(i, 1);
}
}
}
}
// Clear input file in DOM
private clearSelection() {
this.input.type = '';
this.input.type = 'file';
}
}
HTML:
<template>
<input type="file" accept.bind="accept" multiple.bind="multiple"
files.bind="files" ref="input"
style="visibility: hidden; width: 0; height: 0;">
<button class="btn btn-primary" click.delegate="triggerInputClick()">
<slot>Browse...</slot>
</button>
<ul class="list-group" if.bind="validFiles">
<li class="list-group-item" repeat.for="file of validFiles" style="padding: 0; border:none;">
${file.name} <span class="glyphicon glyphicon-remove text-danger" style="cursor: pointer;" click.delegate="removeByFileName(file.name)"></span>
</li>
</ul>
</template>
Parent View Model:
TS:
export class Request {
pageTitle: string = "Request Page";
title: string = '';
description: string = '';
businessValue: string = '';
emails: string = '';
formData: object = {};
public postData() {
this.formData['title'] = this.title;
this.formData['description'] = this.description;
this.formData['businessValue'] = this.businessValue;
this.formData['emails'] = this.emails;
this.formData['attachment'] = [];
console.log(this.formData);
}
}
HTML:
<template>
<require from="./request.css"></require>
<require from="../../resources/elements/file-picker"></require>
<div class="panel panel-primary">
<div class="panel-heading">${pageTitle}</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" value.two-way="title" class="form-control" id="title" placeholder="Brief one-line summary of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input type="text" value.two-way="description" class="form-control" id="description" placeholder="Detailed description of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Business Value</label>
<div class="col-sm-10">
<input type="text" value.two-way="businessValue" class="form-control" id="description" placeholder="Description of how this offers business value">
</div>
</div>
<div class="form-group">
<label for="emails" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" value.two-way="emails" class="form-control" id="emails" placeholder="Provide email address">
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-sm-2 control-label">Attachment(s)</label>
<div class="col-sm-10">
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-default pull-right" click.trigger="postData()">Submit</button>
</div>
</div>
</form>
</div>
</div>
</template>
Any help is really appreciated. :)
You can set up two-way-binding on your Request view, to bind the validFiles in your child view (file-picker) to a variable in your parent view (Request):
request.html:
<file-picker valid-files.two-way="validFiles"></file-picker>
request.ts:
public validFiles: File[];
file-picker.ts:
#bindable
public validFiles: File[];
This way any changes made to the validFiles object in either the child or the parent will update the object in both viewmodels.

Aurelia -- Route Change on Form Submission Issue

Aurelia newbie here and I have hit a wall.
So, this code works just fine and the route change happens, but it only happens after the Submit button on the home.html file is clicked TWICE. On the first Submit button click, I get the following error: ERROR [app-router] Error: Route not found: /anonymous-wow-armory-profile/.
My question is why does it work after two form submissions, but not the first one? I know I am missing something in the process here.
home.html
<template>
<div class="container-fluid">
<div class="row">
<div class="col-md-12 nav-home text-center">
Create Profile
Bug Report
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="logo">
<img src="dist/assets/images/logo.png" alt="Logo" />
</div>
</div>
</div>
<div class="row row-bottom-pad">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="profile-creation-box">
<div class="box-padding">
<strong>Masked Armory</strong> is the most well known anonymous World of Warcraft (WoW) profile source in the Real Money Trading (RMT) market. We take everything to the next level with offering alternate gear sets, sorted reputation display, Feat of Strength / Legacy achievement display, and much more!<br /><br />
Come make a profile at Masked Armory today and see that we are the best solution for all of your anonymous WoW Armory profile needs!
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 container-bottom-pad">
<div class="profile-creation-box">
<div class="box-padding">
<form class="form-horizontal" role="form" submit.delegate="submit()">
<div class="form-group">
<label class="col-sm-3 control-label">Region</label>
<div class="col-sm-9">
<label class="radio-inline">
<input type="radio" name="region_name" value="us" checked.bind="postData.region"> United States
</label>
<label class="radio-inline">
<input type="radio" name="region_name" value="eu" checked.bind="postData.region"> Europe
</label>
</div>
</div>
<div class="form-group">
<label for="server_name" class="col-sm-3 control-label">Server</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="server_name" placeholder="Server Name" value.bind="postData.serverName">
</div>
</div>
<div class="form-group">
<label for="character_name" class="col-sm-3 control-label">Character</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="character_name" name="character_name" placeholder="Character Name" value.bind="postData.characterName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<div class="checkbox">
<label>
<input type="checkbox" id="altgear" name="altgear"> Add Alternate Gearset
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-danger">Create Armory Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
</template>
home.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
import {Router} from 'aurelia-router';
#inject(Router)
export class Home {
postData: Object = {};
data: string = '';
code: string = '';
loading: boolean = false;
http: HttpClient = null;
apiUrl: string = 'http://localhost:8000/api/v1';
constructor(router) {
this.http = new HttpClient().configure(x => {
x.withBaseUrl(this.apiUrl);
x.withHeader('Content-Type', 'application/json');
});
this.maRouter = router;
}
submit() {
console.log(this.postData);
this.http.post('/armory', JSON.stringify(this.postData)).then(response => {
this.data = response.content;
this.code = response.statusCode.toString();
this.loading = false;
});
this.maRouter.navigateToRoute('armory', {id: this.data});
}
}
armory.js
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
export class Armory {
postData: Object = {};
data: string = '';
code: string = '';
loading: boolean = false;
http: HttpClient = null;
apiUrl: string = 'http://localhost:8000/api/v1';
profileId: number = 0;
constructor() {
this.loading = true;
this.http = new HttpClient().configure(x => {
x.withBaseUrl(this.apiUrl);
x.withHeader('Content-Type', 'application/json');
});
}
activate(params, routeConfig) {
this.profileId = params.id;
this.getArmoryData();
}
getArmoryData() {
return this.http.get("/armory/" + this.profileId).then(response => {
this.data = response.content;
console.log(this.data);
this.code = response.statusCode.toString();
this.loading = false;
});
}
}
What am I missing here?
Thanks for your help!
Please, provide your router configuration
Anyway I see some issues already. You try to navigate when this.data is not set, just wait for response:
this.http.post('/armory', JSON.stringify(this.postData)).then(response => {
this.data = response.content;
this.code = response.statusCode.toString();
this.loading = false;
this.maRouter.navigateToRoute('armory', {id: this.data});
});
and we do activate page only if this.getArmoryData() succeed here (if needed), also canActivate() maybe used too
activate(params, routeConfig) {
this.profileId = params.id;
return this.getArmoryData();
}
also would be better to set this.loading = true;, inside armory .activate() and in home.js in submit() before sending data