send JSON data from angular formly to API - http

I want to post the data from an angular formly form to API and I dont know much about fomly and ionic2 combination.The code I tried is not sending my form data to API it is printing error on console.
My .ts code is:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Validators, FormGroup} from '#angular/forms';
import {FormlyFieldConfig} from 'ng-formly';
import { Http,Headers,RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
post = [];
constructor(public navCtrl: NavController,private http : Http) {
}
form: FormGroup = new FormGroup({});
userFields: FormlyFieldConfig = [{
className: 'row',
fieldGroup: [{
className: 'col-xs-6',
key: 'identity',
type: 'input',
templateOptions: {
type: 'email',
label: 'Email address',
placeholder: 'Enter email'
},
validators: {
validation: Validators.compose([Validators.required])
}
}, {
className: 'col-xs-6',
key: 'password',
type: 'input',
templateOptions: {
type: 'password',
label: 'Password',
placeholder: 'Password',
pattern: ''
},
validators: {
validation: Validators.compose([Validators.required])
}
}]
}];
user = {
};
submit(user) {
let url = "http://urbanholic.com/drago/index.php/api/users/login";
let data = {"identity":" ","password":" "}
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({ headers: headers, method: "post" });
this.http.post(url,data,options)
.map(res => res.json())
.subscribe(
data => {
this.post= data.CarRental;
console.log(this.post);
},
/** data => {console.log(data);},*/
err => console.log("error"),
);
}
}
html code is:
<form [formGroup]="form" (ngSubmit)="submit(user)">
<formly-form [model]="user" [fields]="userFields">
<button type="submit" class="btn btn-default" >Button</button>
</formly-form>
</form>

Related

nextjs dynamic() import works in dev mode, but not the production, Nextjs13 pages dir #45582

I have an app with nextjs 13 pages dire.
i am using zoom web sdk for embed the meetings. it works just fine in the dev mode.
the proplem:
when i build the app everything working except that zoom component not showing up after build,
when visiting the /meeting page the component didn't exist.
const ZoomCall = dynamic(() => import("#components/Zoom/ZoomCall"), {
ssr: false,
loading: () => "Loading...",
});
the ZoomCall
import { useEffect } from "react";
import dynamic from "next/dynamic";
import { ZoomMtg } from "#zoomus/websdk";
import ZoomMtgEmbedded from "#zoomus/websdk/embedded";
import ZoomInputs from "./ZoomInputs";
import { useState } from "react";
import useTranslation from "next-translate/useTranslation";
export default function ZoomCall({
user,
meetingNumber,
setMeetingnumber,
passWord,
setMeetingPassword,
}) {
const { t } = useTranslation();
const [isComponentMounted, setIsComponentMounted] = useState(false);
const signatureEndpoint = "/api/zoom/signature";
const role = 0;
useEffect(() => {
ZoomMtg.setZoomJSLib("https://source.zoom.us/1.9.1/lib", "/av");
ZoomMtg.preLoadWasm();
ZoomMtg.prepareJssdk();
}, []);
function getSignature(e) {
e.preventDefault();
fetch(signatureEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
meetingNumber: meetingNumber,
role: role,
}),
})
.then((res) => res.json())
.then((response) => {
startMeeting(response.signature);
})
.catch((error) => {
console.error(error);
});
}
function startMeeting(signature) {
let meetingSDKElement = document.getElementById("meetingSDKElement");
const client = ZoomMtgEmbedded.createClient();
// document.getElementById("zmmtg-root").style.display = "block";
client.init({
debug: true,
zoomAppRoot: meetingSDKElement,
language: "en-US",
customize: {
meetingInfo: [
"topic",
"host",
"mn",
"pwd",
"telPwd",
"invite",
"participant",
"dc",
"enctype",
],
toolbar: {
buttons: [
{
text: "Custom Button",
className: "CustomButton",
onClick: () => {
console.log("custom button");
},
},
],
},
},
});
client.join({
sdkKey: process.env.NEXT_PUBLIC_ZOOM_API_KEY,
signature: signature,
meetingNumber: meetingNumber,
password: passWord,
userName: "..",
userEmail: "ah....",
});
}
return (
<div>
<div id="meetingSDKElement"></div>
<button onClick={getSignature}>Join Meeting</button>
</div>
);
}
I have moved the exports to a index file the export
import dynamic from "next/dynamic";
export default dynamic(() => import("./ZoomCall"), { ssr: false });
the issue in still
i have managed to solve this by changing the :
const ZoomCall = dynamic(() => import("#components/Zoom/ZoomCall"), {
ssr: false,
loading: () => "Loading...",
});
into
export default dynamic(() => import("./ZoomCall").then((mod) => mod.ZoomCall), {
ssr: false,
});
and it works just fine

How to update in Vue3 component content based on reponse data?

Recently I've been working on filters in my service for booking hotel rooms in .NET + Vue3.
Backend method for filtering works fine, but I don't have clue how to force component to update its content using fetched data.
Im reciving data in format like this:
enter image description here
Here are my script and component files:
Filters component:
<template>
<div class="container">
<div class="d-flex align-items-center">
<label for="first_day" class="p-2">First day: </label>
<input type="date" name="first_day" v-model="filtersOptions.FirstDay" />
<label for="last_day" class="p-2">Last day: </label>
<input type="date" name="last_day" v-model="filtersOptions.LastDay"/>
<button type="submit" class="m-2 p-2" v-on:click="fetchFilteredRooms()">Search</button>
</div>
</div>
</template>
<script lang="ts">
import { useFilters } from '#/composables/useFilters';
export default {
setup(props: any, context: any) {
const { filtersOptions, fetchFilteredRooms } = useFilters();
return {
filtersOptions,
fetchFilteredRooms,
}
}
}
</script>
Filters script:
import { ref } from 'vue';
import Consts from "#/consts";
import { useRooms } from './useRooms';
class FiltersOptions {
FirstDay: any;
LastDay: any;
};
const { Rooms } = useRooms();
export const useFilters = () => {
const filtersOptions = ref<any>(new FiltersOptions());
async function fetchFilteredRooms() {
const filterRoomsAPI = Consts.API.concat(`rooms/search`)
const headers = {
'Content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': `${filterRoomsAPI}`
}
fetch(filterRoomsAPI, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
body: JSON.stringify(filtersOptions._value),
headers
})
.then(response => response.json())
.then((data) => (Rooms.value = data))
.catch(error => console.error(error));
}
return {
Rooms,
filtersOptions,
fetchFilteredRooms,
}
}
Rooms component:
import { ref } from 'vue';
import Consts from "#/consts";
import { useRooms } from './useRooms';
class FiltersOptions {
FirstDay: any;
LastDay: any;
};
const { Rooms } = useRooms();
export const useFilters = () => {
const filtersOptions = ref<any>(new FiltersOptions());
async function fetchFilteredRooms() {
const filterRoomsAPI = Consts.API.concat(`rooms/search`)
const headers = {
'Content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': `${filterRoomsAPI}`
}
fetch(filterRoomsAPI, {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
body: JSON.stringify(filtersOptions._value),
headers
})
.then(response => response.json())
.then((data) => (Rooms.value = data))
.catch(error => console.error(error));
}
return {
Rooms,
filtersOptions,
fetchFilteredRooms,
}
}
Rooms script:
import { ref } from 'vue';
import Consts from "#/consts"
const headers = {
'Content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Origin': `${Consts.RoomsAPI}`
}
export function useRooms() {
const Rooms = ref([]);
async function fetchRooms() {
fetch(Consts.RoomsAPI, { headers })
.then(response => response.json())
.then((data) => (Rooms.value = data))
.catch(error => console.log(error));
}
return {
Rooms,
fetchRooms,
};
}
Any idea how to deal with it?

can not call action in Pinia option API

I am using Vue3 option API and Pinia .
I want to call an action in Pinia option Api from component
component
import { mapActions } from "pinia";
import { useTableStore } from "../../../stores/table";
export default {
name: "LoggingForm",
data() {
return {
login: {
username: "",
password: "",
serverhost: "",
},
};
},
methods: {
submit(){
this.getData(this.login)
}
},
computed: {
...mapActions(useTableStore, ["getData"]),
},
};
and this is store/table.js
import { defineStore } from 'pinia'
import authService from "#/api/auth.js";
export const useTableStore = defineStore({
id: 'table',
state: () => ({
table: []
}),
getters: {
headers: (state) => state.table[0],
body: (state) => state.table.slice(1)
},
actions: {
async getData1(data) {
// do something
}
},
}
})
But I get this error
I can Use state and getters perfectly Just action don't work !
what's the problem ?
Here is what you need
https://pinia.vuejs.org/core-concepts/actions.html#without-setup
In short:
computed => mapGetters
methods => mapActions
You are using mapActions with computed so that will not work

Vue3 - Routes if page doesn't exist with dynamic routes not working with my 404?

I am using Vue3 and have my Router setup for detail pages. Any title returns the same data and 404 is being ignored even after adding the regEx inside the routes.
Routes:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import ErrorView from "../views/ErrorView.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
},
{
path: "/article/:slug",
name: "article",
component: () =>
import(/* webpackChunkName: "article" */ "../views/ArticleView.vue"),
},
{
path: "/404",
name: "PageNotExist",
component: () => import("../views/ErrorView.vue"),
},
{
path: "/:catchAll(.*)", // Unrecognized path automatically matches 404
redirect: "/404",
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
Article:
<template>
<div>
<h1>{{ data.title }}</h1>
<h3>{{ data.textarea }}</h3>
</div>
</template>
<script lang="ts">
import { useSanityFetcher } from "vue-sanity";
import { defineComponent } from "vue";
export default defineComponent({
name: "ArticleView",
setup: () => {
const articleQuery = `*[_type == "article"][0] {
title,
textarea,
}`;
const options = {
listen: true,
clientOnly: true,
};
const { data } = useSanityFetcher<object>(articleQuery, options);
return { data };
},
});
</script>

Setting Firebase data to property in html file

Okay so i am fairly new at ionic and i am experiencing this problem where by i am getting the users data from firebase but whenever i set it to the public variable and try and reference it in the html file, i am getting a log error of "cannot set 'variable name' to property of undefined". Here is my code for a more clearer explanation and understanding of what i am trying to achieve. Thank you.
.ts file:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,AlertController,
LoadingController, Loading } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import { MenuPage } from '../menu/menu';
import firebase from 'firebase';
import { first } from 'rxjs/operators';
#IonicPage()
#Component({
selector: 'page-account',
templateUrl: 'account.html',
})
export class AccountPage {
public userinfo;
constructor(public navCtrl: NavController, public navParams: NavParams,
private alertCtrl:AlertController, public fAuth:AngularFireAuth,
public loading:LoadingController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad AccountPage');
this.readData();
}
isLoggedIn(){
return this.fAuth.authState.pipe(first()).toPromise();
}
userStatus(){
const user = this.isLoggedIn()
if(user){
console.log('logged in');
this.readData();
}else{
}
}
async readData(){
let load = this.loading.create({
content: "Setting up your profile...",
spinner:'dots'
});
load.present();
await this.fAuth.authState.subscribe((user:firebase.User) =>{
if(user){
firebase.database().ref('/users/' +
user.uid).once('value').then(function(snapshot){
if(snapshot.exists()){
var data = (snapshot.val() && snapshot.val().username) ||
'Anonymous';
//this.userinfo = data;
console.log(data);
}else{
console.log("i need a name");
}});
}else{
console.log("not logged in, log in please");
this.alertLogin();
};
});
console.log(this.userinfo );
load.dismiss();
}
getName(){
let alert = this.alertCtrl.create({
title: 'Hello new friend! :) please can you tell us your name...',
inputs: [
{
name: 'name',
placeholder: 'name'
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
this.navCtrl.setRoot(MenuPage);
}
},
{
text: 'Confirm',
handler: data => {
this.fAuth.authState.subscribe((user:firebase.User) =>{
firebase.database().ref('/users/' + user.uid).set({
username:data.name
});
});
}
}
]
});
alert.present();
}
alertLogin(){
//if user is not already logged in
let alert = this.alertCtrl.create({
title: 'Whoa there Sally! you need to log in first! :)',
inputs: [
{
name: 'email',
placeholder: 'email'
},
{
name: 'password',
placeholder: 'Password',
type: 'password'
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
this.navCtrl.setRoot(MenuPage);
}
},
{
text: 'Login',
handler: data => {
this.login(data.email,data.password);
}
},{
text: 'Register',
handler: data => {
this.register(data.email,data.password);
}
}
]
});
alert.present();
}
async login(email,password){
try{
var login = await this.fAuth.auth.signInWithEmailAndPassword(
email,
password
);
if(login){
console.log("Successfully logged in!");
}
}catch(err){
console.error(err);
alert("Sorry we couldnt find you in our system :(");
this.navCtrl.setRoot(MenuPage);
}
}
async register(email,password){
try{
var reg = await this.fAuth.auth.createUserWithEmailAndPassword(
email,
password
);
if(reg){
this.getName();
console.log("successfully registered!");
this.navCtrl.setRoot(AccountPage);
}
}catch(err){
console.error(err);
}
}
logout(){
this.fAuth.auth.signOut();
}
}
.html file:
<ion-item>
<h1>{{userinfo}}</h1>
</ion-item>
Okay so i have tried basically everything and have decided to rather just upload the name to the database and write it locally in the storage of the application. I will just pull the name, along with further details later on in the application process. However if anyone finds an answer for this post, i would greatly appreciate it!

Resources