what should i use istead of ans if i want to make a list? - vue.js

what should i use istead of ans if i want to make a list? I tried putting more ans var but it doesn't work only displays the last ans
<script setup>
import { ref } from "#vue/reactivity";
const faqToggle = ref(false);
const faqItems = ref([
** {
title: "test",
ans: "· test1",
id: 1,
},**
]);
const id = ref(null);
const toggle = (fid) => {
if (fid === id.value) {
faqToggle.value = !faqToggle.value;
} else {
faqToggle.value = true;
}
id.value = fid;
};
</script>
title: "test",
ans: "· test1",
ans: "· test2",
ans: "· test3",
ans: "· test4",
id: 1,

Related

geographicToWebMercator and Projected polygon appears only after click on zoom buttons angular 10

I am using geographicToWebMercator to draw a specific area on my map. The Polygon should draw as soon as the map loads. But the polygon is appearing only after click on the zoom buttons. either zoom in or zoom out. The code was working fine in arcgis 4.16 I have the upgraded version 4.16 to ArcGIS version 4.18.
Please find the code below,
import {
Component,
OnInit,
ViewChild,
ElementRef,
Input,
Output,
EventEmitter,
OnDestroy,
NgZone
} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { GisService } from '../search/gis.service';
import { ActivatedRoute, Router } from '#angular/router';
import { map } from 'rxjs/operators';
import { loadScript, loadModules } from 'esri-loader';
import esri = __esri; // Esri TypeScript Types
import { empty } from 'rxjs';
import { AppConfig } from '../config/app.config';
#Component({
selector: 'app-esri-map',
templateUrl: './esri-map.component.html',
styleUrls: ['./esri-map.component.css'],
})
export class EsriMapComponent implements OnInit, OnDestroy {
#Output() mapLoadedEvent = new EventEmitter<boolean>();
#ViewChild('mapViewNode', { static: true }) private mapViewEl: ElementRef;
view: any;
dynamicRings: any;
wkid: any;
addr: any;
loadingmap = true;
// to keep loaded esri modules
esriModules = {
graphic: null,
geometry: {
Polygon: null,
SpatialReference: null,
support: { webMercatorUtils: null },
},
tasks: {
GeometryService: null,
support: { ProjectParameters: null },
},
};
private _zoom = 20;
private _center: Array<number> = [-95.937187, 41.258652];
private _basemap = 'gray-vector';
private _loaded = false;
private _view: esri.MapView = null;
private _nextBasemap = 'streets';
public _selectedLayer: Array<string>;
public layersMapIdxArray: string[] = ['0', '1', '2'];
public mapalllayerview: boolean;
public layersDic = {};
private readonly esriMapUri: string;
private readonly gisGeometryServer: string;
get mapLoaded(): boolean {
return this._loaded;
}
#Input()
set zoom(zoom: number) {
this._zoom = zoom;
}
get zoom(): number {
return this._zoom;
}
#Input()
set center(center: Array<number>) {
this._center = center;
}
get center(): Array<number> {
return this._center;
}
#Input()
set basemap(basemap: string) {
this._basemap = basemap;
}
get basemap(): string {
return this._basemap;
}
#Input()
set nextBasemap(nextBasemap: string) {
this._nextBasemap = nextBasemap;
}
get nextBasemap(): string {
return this._nextBasemap;
}
public onLayerChange(val: Array<string>) {
// hide all the layers before showing the selected layers
for (const al of this.layersMapIdxArray) {
this.layersDic[al].visible = false;
}
// layersDic is the feature layers added to the map
for (const v of val) {
this.layersDic[v].visible = true;
}
}
constructor(
private gisService: GisService,
private http: HttpClient,
private route: ActivatedRoute,
private router: Router,
private zone: NgZone,
private appConfig: AppConfig) {
this.esriMapUri = this.appConfig.getGisMapURL('');
this.gisGeometryServer = this.appConfig.gisGeometryServer('');
}
async initializeMap() {
try {
loadScript();
// Load the modules for the ArcGIS API for JavaScript
const [
EsriMap,
EsriMapView,
Polygon,
SpatialReference,
webMercatorUtils,
GeometryService,
ProjectParameters,
FeatureLayer,
BasemapToggle,
BasemapGallery,
Graphic,
] = await loadModules([
'esri/Map',
'esri/views/MapView',
'esri/geometry/Polygon',
'esri/geometry/SpatialReference',
'esri/geometry/support/webMercatorUtils',
'esri/tasks/GeometryService',
'esri/tasks/support/ProjectParameters',
'esri/layers/FeatureLayer',
'esri/widgets/BasemapToggle',
'esri/widgets/BasemapGallery',
'esri/Graphic',
]);
// save the modules on a property for later
this.esriModules.geometry.Polygon = Polygon;
this.esriModules.geometry.SpatialReference = SpatialReference;
this.esriModules.geometry.support.webMercatorUtils = webMercatorUtils;
this.esriModules.tasks.GeometryService = GeometryService;
this.esriModules.tasks.support.ProjectParameters = ProjectParameters;
this.esriModules.graphic = Graphic;
// Configure the Map
const mapProperties: esri.MapProperties = {
basemap: this._basemap,
};
const map: esri.Map = new EsriMap(mapProperties);
// Initialize the MapView
const mapViewProperties: esri.MapViewProperties = {
container: this.mapViewEl.nativeElement,
// center: this._center,
zoom: this._zoom,
map: map,
};
this._view = new EsriMapView(mapViewProperties);
// Add layers to the map according to the selection
for (const idx of this.layersMapIdxArray) {
this.layersDic[idx] = new FeatureLayer({
url: `${this.esriMapUri}/${idx}`,
visible: this.mapalllayerview,
outFields: ['*'],
});
map.add(this.layersDic[idx]);
}
// The layer 15 will be the stack at the top of the layers so 15 will be consider first layer
this.layersDic[15] = new FeatureLayer({
url: `${this.esriMapUri}/15`,
visible: true,
outFields: ['*'],
});
map.add(this.layersDic[15]);
// Basemap toglle section
var basemapToggle = new BasemapToggle({
view: this._view,
nextBasemap: this._nextBasemap,
});
this._view.ui.add(basemapToggle, 'bottom-right');
// Load details of SAID when click on the map
let hitself = this;
this._view.on('click', function (event) {
hitself._view
.hitTest(event, { exclude: hitself._view.graphics })
.then(function (response) {
console.log(response);
if (
typeof response.results !== 'undefined' &&
response.results.length > 0
) {
var graphic = response.results[0].graphic;
var attributes = graphic.attributes;
var category = attributes.ADDRESS;
// redirect to the corresponding SAID
// window.location.href = `/dashboard/${category}`;
// hitself.router.navigate(['dashboard', category]);
hitself.addr = category;
var dashurl = 'search/detail/' + hitself.addr;
hitself.zone.run(() => {
hitself.router.navigateByUrl(dashurl);
});
}
});
return;
});
await this._view.when(); // wait for map to load
return this._view;
} catch (error) {
console.error('EsriLoader: ', error);
}
}
// point geometry extent is null
zoomToGeometry(geom) {
// console.log(`Original Geometry: ${JSON.stringify(geom.toJSON())}`);
const geomSer = new this.esriModules.tasks.GeometryService(this.gisGeometryServer);
const outSpatialReference = new this.esriModules.geometry.SpatialReference({
wkid: 102100,
});
const params = new this.esriModules.tasks.support.ProjectParameters({
geometries: [geom],
outSpatialReference,
});
const self = this;
geomSer
.project(params)
.then(function (result) {
const projectedGeom = result[0];
if (!projectedGeom) {
return;
}
// console.log(
// `Projected Geometry: ${JSON.stringify(projectedGeom.toJSON())}`
// );
return projectedGeom;
})
.then(function (polly) {
// console.log(self.esriModules.graphic);
self._view.graphics.add(
new self.esriModules.graphic({
geometry: polly,
symbol: {
type: 'simple-fill',
style: 'solid',
color: [255, 0, 0, 0.1],
outline: {
width: 1,
color: [255, 0, 0, 1],
},
},
})
);
self._view.extent = polly.extent.clone().expand(3);
});
}
ngOnInit() {
this.route.paramMap.subscribe((params) => {
this.addr = params.get('address');
console.log(this.addr);
this.gisService.getAddressDetails(this.addr).subscribe((posts) => {
const get_wkid = posts[0]['spatialReference'];
this.wkid = get_wkid['wkid'];
const dynamicrings = posts[0]['features'];
this.dynamicRings = dynamicrings[0]['geometry']['rings'];
});
this._selectedLayer = ['1', '0', '2'];
// this.layersMapIdxArray = this._selectedLayer;
this.mapalllayerview = true;
this.initializeMap().then(() => {
// The map has been initialized
console.log('mapView ready: ', this._view.ready);
const geom = new this.esriModules.geometry.Polygon({
spatialReference: {
wkid: this.wkid, //102704,
},
rings: this.dynamicRings,
});
this.zoomToGeometry(geom);
console.log('mapView ready: ', this._view.ready);
this._loaded = this._view.ready;
this.mapLoadedEvent.emit(true);
this.loadingmap = false;
});
});
}
ngOnDestroy() {
if (this._view) {
// destroy the map view
this._view.container = null;
}
}
}

Can't pass my data to the mounted() method

I am fairly new to Vue so excuse my stupidity!!
Can anyone tell me what I am doing wrong in my code below that is preventing me from getting my 'series_interactions_daily' variable data from inside the mounted() method please? I am console.log()'ing it but nothing shows! I can print 'series_interactions_daily' to screen in the HTML though!
<script>
import * as am4core from "#amcharts/amcharts4/core";
import * as am4charts from "#amcharts/amcharts4/charts";
import am4themes_animated from "#amcharts/amcharts4/themes/animated";
am4core.useTheme(am4themes_animated);
export default {
mounted() {
let chart = am4core.create(this.$refs.chartdiv, am4charts.XYChart);
chart.paddingRight = 20;
let dummydata = [];
let visits = 10;
for (let i = 1; i < 366; i++) {
visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
dummydata.push({ date: new Date(2018, 0, i), name: "name" + i, value: visits });
}
chart.data = dummydata;
console.log(this.series_interactions_daily);
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
valueAxis.renderer.minWidth = 35;
let series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY.value}";
chart.cursor = new am4charts.XYCursor();
let scrollbarX = new am4charts.XYChartScrollbar();
scrollbarX.series.push(series);
chart.scrollbarX = scrollbarX;
this.chart = chart;
},
beforeDestroy() {
if (this.chart) {
this.chart.dispose();
}
},
data() {
return {
campaign_id: this.$route.params.campaign_id,
campaign: [],
dateranges: [],
total_interactions: '',
average_daily_interactions: '',
series_interactions_daily: [],
}
},
methods: {
onChange(event) {
this.$router.push('?range=' + event.target.value);
this.$http.get('https://dev.local/api/portal/campaign/' + this.campaign_id + '?range=' + event.target.value)
.then(function(data){
return data.json();
}).then(function(data){
this.campaign = data.campaign;
this.dateranges = data.dateranges;
this.total_interactions = data.totalInteractions;
this.average_daily_interactions = data.averagreDailyInteractions;
this.series_interactions_daily = data.interactions_per_day.stats.interaction.daily;
});
}
},
created() {
this.$http.get('https://dev.local/api/portal/campaign/' + this.campaign_id + '?' + this.axiosParams)
.then(function(data){
return data.json();
}).then(function(data){
this.campaign = data.campaign;
this.dateranges = data.dateranges;
this.total_interactions = data.totalInteractions;
this.average_daily_interactions = data.averagreDailyInteractions;
this.series_interactions_daily = data.interactions_per_day.stats.interaction.daily;
});
},
computed: {
axiosParams() {
const params = new URLSearchParams();
if(this.$route.query.range) params.append('range', this.$route.query.range);
return params;
}
},
filters: {
},
directives: {
},
}
</script>
EDIT
OK, so I have create a method to fetchData() from mounted(){} - however I am still not getting my 'series_interactions_daily' variable data!
<script>
import * as am4core from "#amcharts/amcharts4/core";
import * as am4charts from "#amcharts/amcharts4/charts";
import am4themes_animated from "#amcharts/amcharts4/themes/animated";
am4core.useTheme(am4themes_animated);
export default {
mounted() {
this.fetchData();
let chart = am4core.create(this.$refs.chartdiv, am4charts.XYChart);
chart.paddingRight = 20;
let dummydata = [];
let visits = 10;
for (let i = 1; i < 366; i++) {
visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10);
dummydata.push({ date: new Date(2018, 0, i), name: "name" + i, value: visits });
}
chart.data = dummydata;
console.log(this.series_interactions_daily);
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.tooltip.disabled = true;
valueAxis.renderer.minWidth = 35;
let series = chart.series.push(new am4charts.LineSeries());
series.dataFields.dateX = "date";
series.dataFields.valueY = "value";
series.tooltipText = "{valueY.value}";
chart.cursor = new am4charts.XYCursor();
let scrollbarX = new am4charts.XYChartScrollbar();
scrollbarX.series.push(series);
chart.scrollbarX = scrollbarX;
this.chart = chart;
},
beforeDestroy() {
if (this.chart) {
this.chart.dispose();
}
},
data() {
return {
campaign_id: this.$route.params.campaign_id,
campaign: [],
dateranges: [],
total_interactions: '',
average_daily_interactions: '',
series_interactions_daily: [],
}
},
methods: {
fetchData() {
this.$http.get('https://dev.local/api/portal/campaign/' + this.campaign_id + '?' + this.axiosParams)
.then(function(data){
return data.json();
}).then(function(data){
this.campaign = data.campaign;
this.dateranges = data.dateranges;
this.total_interactions = data.totalInteractions;
this.average_daily_interactions = data.averagreDailyInteractions;
this.series_interactions_daily = data.interactions_per_day.stats.interaction.daily;
});
},
onChange(event) {
this.$router.push('?range=' + event.target.value);
this.$http.get('https://connie.laravel/api/portal/campaign/' + this.campaign_id + '?range=' + event.target.value)
.then(function(data){
return data.json();
}).then(function(data){
this.campaign = data.campaign;
this.dateranges = data.dateranges;
this.total_interactions = data.totalInteractions;
this.average_daily_interactions = data.averagreDailyInteractions;
this.series_interactions_daily = data.interactions_per_day.stats.interaction.daily;
});
}
},
created() {
},
computed: {
axiosParams() {
const params = new URLSearchParams();
if(this.$route.query.range) params.append('range', this.$route.query.range);
return params;
}
},
filters: {
},
directives: {
},
}
</script>
Any help appreciated.
Thanks,
K...
In fetchData, return the promise returned by the async $http call:
fetchData() {
return this.$http.get(...)
...
}
Now you can register a callback on that promise in mounted:
mounted() {
this.fetchData().then(result => {
...
});
}
Or just await it with async/await:
async mounted() {
await this.fetchData();
...
// Now everything will be ready
}
As #tao mentioned in comments, note that the await would delay any code that comes after it. If you don't have anything else to do in the hook anyway that's no problem but it's something to understand.

How to Load data dynamically to multiselect Option in VueJs

I need to load the data dynamically to multi select option using VueJs.
I tried lot of ways but nothing is worked for me. this is my codes
<multiselect id="webbrand" v-model="upallwebbrand" data-validation="required" data-validate-name="WebBrand"
:options="webbrands"
:multiple="true"
track-by="code"
:custom-label="websites"
placeholder="Please select deafult website first">
</multiselect>
Vue Function
showdata: function (staffid) {
axios.post("/HR/Showdata/", null, { params: { staffid } }).then(function (response)
{
hrform.oripassword = response.data.password;
hrform.upusername = response.data.userdata.UserName;
hrform.staffid = response.data.userdata.EmployeeId;
hrform.upselectedteam = response.data.userdata.TeamId;
hrform.upaccesslevel = response.data.userdata.AccessLevel;
hrform.upselectedstatus = response.data.userdata.Status;
hrform.upemail = response.data.userdata.Email;
**//hrform.upallwebbrand = response.data.userdata.BrandId**
hrform.upallwebbrand = [{ name: 'Travelcenter', code: 'TCUK' },
{ name: 'Tour Center', code: 'TOUR' },
{ name: 'World Airfairs', code: 'WAFR' },
{ name: 'Mabuhay', code: 'MABU' }];
hrform.upselectdesignation = response.data.userdata.Designation;
});
},
websites: function (option) {
return `${option.name} - ${option.code}`
},
In bove function BrandId is coming like this TCUK,WAFR,TOUR,MABU, only code with comma separated
I want to make it like below
[
{ name: 'Travelcenter', code: 'TCUK' },
{ name: 'Tour Center', code: 'TOUR' },
{ name: 'World Airfairs', code: 'WAFR' },
{ name: 'Mabuhay', code: 'MABU' }
]
If assigned values manually like above it's working fine.
I have to do it dynamically How can I achieve this??
Lets assume you have 2 arrays, one for name and one for code which is in the right order. You can create an array of objects like this
var name_arr = ['name1', 'name2', 'name3']
var code_arr = ['code1', 'code2', 'code3']
var upallwebbrand = []
for(var i=0; i<name_arr.length; i++){
upallwebbrand.push({
name: name_arr[i],
code: code_arr[i]
});
}
I'm Posting this for future viewers..
var hrform = new Vue({
el: '#hrform',
data: {
upselectdesignation:'',
upallwebbrand : [] //I defined the array like this
},
});
And while updating the upallwebbrand getting the codes from database and did the for loop to push the data to array upallwebbrand like below
showdata: function (staffid) {
axios.post("/HR/Showdata/", null, { params: { staffid } }).then(function (response) {
hrform.oripassword = response.data.password;
hrform.upusername = response.data.userdata.UserName;
hrform.staffid = response.data.userdata.EmployeeId;
hrform.upselectedteam = response.data.userdata.TeamId;
hrform.upaccesslevel = response.data.userdata.AccessLevel;
hrform.upselectedstatus = response.data.userdata.Status;
hrform.upemail = response.data.userdata.Email;
hrform.upselectdesignation = response.data.userdata.Designation;
//hrform.branss = response.data.userdata.BrandId;
var codes = response.data.userdata.BrandId.split(","); // Spliting the brand Id
var obj = { 'TCUK': 'Travel Center', 'MABU': 'Mabuhai', 'WAFR': 'World AirFares', 'TOUR': 'Tour Center' }
hrform.upallwebbrand = [];
for (var i = 0; i < codes.length; i++)
{
if (codes[i] in obj) {
hrform.upallwebbrand.push({ code: codes[i], name: obj[codes[i]] })
}
}
});
}

Ramda, filter with or condition

let arr = [
{
name: 'Anna',
q: {
name: 'Jane'
}
}
];
const getName = R.prop('name');
const getQname = R.path(['q','name']);
A filter where any of these two functions passes.
Something like:
export const filterByName = (name) =>
R.filter(
R.or(
R.propEq(getName, name),
R.propEq(getQname, name)
)
)
Not working. How can I combine these two functions in a R.filter?
Use R.either with R.propEq for the name and R.pathEq from q.name:
const filterByName = (name) =>
R.filter(
R.either(
R.propEq('name', name),
R.pathEq(['q', 'name'], name)
)
)
const arr = [{"name":"Anna","q":{"name":"Jane"}},{"name":"Smite","q":{"name":"Jane"}},{"name":"Another","q":{"name":"One"}}];
console.log(filterByName('Anna')(arr))
console.log(filterByName('Jane')(arr))
console.log(filterByName('XXX')(arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
If you want to use an external function to extract the values, you can use R.pipe. Extract all property values with R.juxt, and then use R.any with R.equal to check for equality.
const getName = R.prop('name');
const getQname = R.path(['q','name']);
const filterByName = (name) =>
R.filter(
R.pipe(
R.juxt([getName, getQname]), // get all names
R.any(R.equals(name)) // check if any of the equals to name
)
)
const arr = [{"name":"Anna","q":{"name":"Jane"}},{"name":"Smite","q":{"name":"Jane"}},{"name":"Another","q":{"name":"One"}}];
console.log(filterByName('Anna')(arr))
console.log(filterByName('Jane')(arr))
console.log(filterByName('XXX')(arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
I would use either as it works with functions:
export const filterByName = (name) =>
R.filter(R.either(
R.propEq('name', name),
R.pathEq(['q', 'name'], name)));
or
const nameIs = R.propEq('name');
const qNameIs = R.pathEq(['q','name']);
export const filterByName = (name) =>
R.filter(R.either(nameIs(name), qNameIs(name)));
You could also write this in a point free style:
const nameIs = R.converge(R.or, [
R.pathEq(['name']),
R.pathEq(['q', 'name']),
]);
const onlyAnna = R.filter(nameIs('Anna'));
const onlyGiuseppe = R.filter(nameIs('Giuseppe'));
const data = [
{ name: 'Anna', q: { name: 'Jane' } },
{ name: 'Mark', q: { name: 'Mark' } },
{ name: 'Giuseppe', q: { name: 'Hitmands' } },
];
console.log('Anna', onlyAnna(data));
console.log('Giuseppe', onlyGiuseppe(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance