Not uploading CSV file in vue.js - csv

I have started with vue and D3. I just want to show my csv data in the console but when I try to do it with D3 CSV function is not working at all. Appears an array of 16 HTML elements which are in index.html, would you mind helping me with this?
This is my project structure:
This is my component code:
<template>
</template>
<script>
import * as d3 from "d3";
import { csv } from 'd3';
export default {
name: 'mycomponent',
data() {
return{
dataset: [],
}
},
async mounted(){
const data = await d3.csv('./datasets/dataset.csv')
this.$data.$dataset = Object.freeze(data)
console.log(data);
}
}
</script>
This is home:
<template>
<mycomponent></mycomponent>
</template>
<script>
import mycomponent from '#/components/mycomponent.vue'
export default {
name: 'Home',
components: {
mycomponent,
},
}
</script>
And this is what I get in console:

The d3.csv function will execute at runtime not compile-time so you have to put your csv file in public directory then use it as usual public files.
let data = await d3.csv("/datasets/dataset.csv")
Or if you want to load your csv file at compile-time you can import it as string and use d3.csvParse instead.
import dataset from '#/datasets/dataset.csv'
let data = d3.csvParse(dataset);
I would prefer the first method, in the second method your csv file might cause your script file too big.
Example

Related

How do we actually register a customised formatter in react vega?

I have read the documentation so many times https://vega.github.io/vega-lite/docs/config.html#custom-format-type. I still don't understand how to implement this in react vega. What confuses me the most is this vega object.
view = new vega.View(...);
view.expressionFunction('customFormatA', function(datum, params) {
...
return "<formatted string>";
});
What I am currently doing in React:
import React from "react";
import ReactDOM from "react-dom";
import { createClassFromSpec } from "react-vega";
const spec = {}
const BarChart = createClassFromSpec({ mode: "vega-lite", spec: spec });
export default function TestPage2({ data }) {
return <BarChart data={{ table: data }} />;
}
Is there any example of implementing a custom format type that I can learn from?
There was an error in the documentation and a pull request has been submitted.
You should use vega instead of vega.View like so:
import { expressionFunction } from 'vega';
expressionFunction('customFormatA', function(datum, params) {
return datum;
});
However, note that custom formats do not work with binning; an issue has been opened for this.

ES6 import function - execute in Vue component

In my Vue app I have JS file with some config data. In JS file there is export function. I'm importing this function to my Vue component but it's returning function declaration as a string. How can I make that function to return it's return data?
JS file
export function Test(app) {
return [ some data... ]
}
Vue component
import { Test } from '#/config/Test'
export default {
data() {
return {
testData: Test,
}
},
}

access store outside of component vuejs

I have a file for configuring my OpenID Connect authentication
export const authMgr = new Oidc.UserManager({
userStore: new Oidc.WebStorageStateStore(),
authority: **appsetting.oidc**
})
I want to access my state in order to get the value of appsetting.
I did this:
import store from './store'
const appsetting = () => store.getters.appsetting
but my appsetting is always returning undefined
what I my missing?
Store:
app.js
const state = {
appsetting: appsetting,
}
export {
state
}
getters.js
const appsetting = state => state.appsetting
export {
appsetting
}
index.js
export default new Vuex.Store({
actions,
getters,
modules: {
app
},
strict: debug,
plugins: [createLogger]
})
when I print the value of store.getters, it returns this:
{
return __WEBPACK_IMPORTED_MODULE_2__store__["a" /* default */].getters;
}
No the actual store objects
Try to import 'store' with curly brackets
import {store} from '../store/index'
store.getters.appSettings
Another option is to access from the vue property
import Vue from 'vue'
Vue.store.getters.appSettings
As for 2023 accesing store with
import {store} from '../store/index'
store.getters.appSettings
wasnt working for me but after removing curly brackets like so:
import store from '../store/index'
store.getters.appSettings
It started working as intended

Problems to map a json with axios.get

My name is Jose and i'm trying to fetch data Json in an array to be displayed with react. My json file is:
[{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}...
My js file is:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
import './index.css';
class Ramas extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount(){
axios
.get('../proceso.json')
.then(({ data })=> {
this.setState({
data
});
})
.catch((err)=> {console.log('no recibido')})
}
I do not get any results. I appreciate any help.
My folder structure:
react_root
-nodemodules
-public
--index.html
-src
--index.js
The json file is in vps.../fuentes/proceso.json. It's another server an i can access to it via url
Thank you
There is no need of axios for this,
The real use of axios is when you want to fetch data from API or out of your server , if proceso.js was on a different server then its good to use.
What you can do is create one file ;
// proceso.js
export default [
{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}
...
]
Then use it like :
import proceso from 'path/to/proceso.js';
componentDidMount(){
this.setState({
data : proceso
});
}
If your json file is being updated by server then put the file inside public folder and then try to call axios via public folder path,
Because once the build is generated, you will not be able to access other directories, like src directory

Load Config JSON File In Angular 2

I want to load Constant File in Angular 2(which is a Normal TypeScript File) having WebAPI EndPoints.
In Angular1.x. we used to have constants for the same.
How in Angular 2 I can Implement the Same?
I have created the .ts file.My main concern lies in how to load the file beforehand every Other class File loads.
.ts file :
export class testAPI {
getAPI = "myUrl";
}
In service file I am using the same by doing Normal Import:
constructor(private http: Http) {
//console.log(this.test);
console.log(this.testing.getAPI);
//this.test.load();
}
I am getting the Console as Undefined.(Must be because my Service class is loading before API Class).
Thanks in Advance.
UPDATES
Inspired with the solution for this particular problem created ngx-envconfig package and published it on NPM registery. It has the same functionalities as it is provided in this answer and even more.
You can have the JSON file somewhere in assets folder like: assets/config. Depending on whether the environment is dev or not you can use two .json files, one for development and one for production. So you can have development.json and production.json files, where each one will keep the appropriate API endpoints.
Basically you need to go through the following steps:
1. Setting up environment (skip this step if you have it already)
Create two files in src/environments folder:
environment.prod.ts
export const environment = {
production: true
};
environment.ts
export const environment = {
production: false
};
2. Create JSON config files
assets/config/production.json
{
"debugging": false,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
assets/config/development.json
{
"debugging": true,
"API_ENDPOINTS": {
"USER": "api/v1/user",
...
}
}
3. Create a service as follows
Note depending on the environment, the ConfigService will load the appropriate file
import { Injectable, APP_INITIALIZER } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs';
import { environment } from 'environments/environment'; //path to your environment files
#Injectable()
export class ConfigService {
private _config: Object
private _env: string;
constructor(private _http: Http) { }
load() {
return new Promise((resolve, reject) => {
this._env = 'development';
if (environment.production)
this._env = 'production';
console.log(this._env)
this._http.get('./assets/config/' + this._env + '.json')
.map(res => res.json())
.subscribe((data) => {
this._config = data;
resolve(true);
},
(error: any) => {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
});
});
}
// Is app in the development mode?
isDevmode() {
return this._env === 'development';
}
// Gets API route based on the provided key
getApi(key: string): string {
return this._config["API_ENDPOINTS"][key];
}
// Gets a value of specified property in the configuration file
get(key: any) {
return this._config[key];
}
}
export function ConfigFactory(config: ConfigService) {
return () => config.load();
}
export function init() {
return {
provide: APP_INITIALIZER,
useFactory: ConfigFactory,
deps: [ConfigService],
multi: true
}
}
const ConfigModule = {
init: init
}
export { ConfigModule };
4. Integrate with app.module.ts
import { NgModule } from '#angular/core';
import { ConfigModule, ConfigService } from './config/config.service';
#NgModule({
imports: [
...
],
providers: [
...
ConfigService,
ConfigModule.init(),
...
]
})
export class AppModule { }
Now you can use ConfigService wherever you want get the necessary API endpoints defined in config .json files.
In Angular 4+ projects generated with the Angular CLI, you will have the environment folder out-of-the-box. Inside of it, you will find the environment.ts files from Karlen's answer. That is a working solution for configuration with one caveat: Your environment variables are captured at build time.
Why does that matter?
When you're setting up a CI/CD pipeline for your Angular app, you will generally have a build tool that builds your project (like Jenkins) and a deployment tool (like Octopus) that will grab that package (the dist folder) and deploy to the selected environment, replacing your environment variables with the correct values in the process. If you use the environment.ts files, your environment variables cannot be replaced this way because the environment.ts files do not get included in the dist folder. There is no file your deployment tool can pick up and edit.
What can we do? we can add a JSON configuration file inside of the assets folder. Those files are included by default in the dist folder we will want to deploy. When we want to use an environment variable, we simply import the settings like import config from '[relative/path/to/your/config/file.json]'.
When we do this, we will get something like the following error:
Cannot find module '../../config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
This is because the typescript compiler tries to import an exported module and cannot find one. We can fix this by adding the following JSON properties/values in our tsconfig.json file.
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
resolveJsonModule allows the typescript compiler to import, extract types from, and generate .json files.
allowSyntheticDefaultImports allows default imports from modules with no default export.
With this in place, we can run our project and we will find that our error is gone and we can use our config values without any issues.
Now, because this config file is included in the dist folder that gets deployed on the server, we can configure our deployment tool to replace the variable values with the values specific to the environment to which we want to deploy. With this in place we can build our Angular app once and deploy it anywhere.
Another added benefit is that most deployment tools like Octopus ship with native JSON support so you can configure it to replace environment variables in your JSON file quite easily. The alternative is using a regex solution to replace environment variables in a .ts file, which is comparatively more complicated and prone to mistakes.
It is possible to import JSON in TypeScript. You need to add typings:
typings.d.ts:
declare module "*.json" {
const value: any;
export default value;
}
And then import like this:
import config from "../config/config.json";
config.json:
{
"api_url": "http://localhost/dev"
}
I had same issue and in the end i give up from .ts and put it in .js :D like this:
configuration.js in root
var configuration = {
'apiHost': 'http://localhost:8900',
'enableInMemoryWebApi': false,
'authMode': 'standalone',
'wsUrl': 'ws://localhost:8900/ws'
};
module.exports = configuration;
in .ts file for ex. user.service.ts
let configuration = require('../configuration'); //in import section
#Injectable()
export class UserService {
...
getUser(id: number | string): Promise<User> {
console.log(configuration.apiHost) //will get propertye from .js file
return this.http.get(`${configuration.apiHost}/${id}`, this.headers).toPromise().then(this.extractData).catch(this.handleError);
}
}
Hope it helps
You can use Opague token to set constant values as providers
Try:
In your const file:
import { OpaqueToken } from '#angular/core';
export const CONFIG_TOKEN = new OpaqueToken('config');
export const CONFIG = {
apiUrl: 'myUrl'
};
In your AppModule set to make it a singleton provider for the app:
providers:[
//other providers,
{provide: CONFIG_TOKEN, useValue: CONFIG}
]
For injecting in constructor,
constructor( #Inject(CONFIG_TOKEN) private config)