How to Pass data from api into pie chart with angular - node.js

I would like to pass the output of an API in a piechart canvas with angular but I could not achieve any result, the API is consumed but I have a problem associating it with the piechart (datapoints)
the code just below.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { EmailValidator } from '#angular/forms';
import { Router, NavigationEnd } from '#angular/router';
import { ApiService } from './api.service';
import { ApistatService } from './apistat.service';
import * as CanvasJS from './canvasjs.min';
//var CanvasJS = require('./canvasjs.min');
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
elements: any[];
constructor(
private apistatService: ApistatService
) {
this.elements = [];
}
ngOnInit() {
let chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
animationEnabled: true,
exportEnabled: true,
title:{
text: "Monthly Expense"
},
data: [{
type: "pie",
showInLegend: true,
toolTipContent: "<b>{elements.total}</b>: ${y} (#status)",
indexLabel: "{name} - #percent%",
dataPoints: [
{ y: 120, name: "Insurance" },
{ y: 300, name: "Traveling" },
{ y: 800, name: "Housing" },
{ y: 150, name: "Education" },
{ y: 150, name: "Shopping"},
{ y: 250, name: "Others" }
]
}]
});
this.apistatService.getData().subscribe((data:any) => {
if(data.status === 200) {
console.log(data.response);
this.elements = data.response;
}
})
chart.render();
}
}
app.component.html
<div id="chartContainer" style="height: 370px; width: 100%; margin-left:auto;margin-right:auto;">
</div>

To consume API data in pie chart you should just set data from API to dataPoints array just make sure your API data has same formatting as currently available inside dataPoints array which you are passing in data array while rendering chart, and it will work.

Related

Angular Get Data From JSON to Model And List It

I'm trying to get data from a JSON using Angular and map it to a model, then show it on a webpage.
I did it buy I'm not getting any results, like the data from JSON cannot be taken or something.
Here's my try:
The JSON:
{
"location": [
{
"_id": "5f3567a8d8e66b41d4bdfe5f",
"lat": "44.4363228",
"lng": "25.9912305",
"token": "edb153fb9d8d5628",
"__v": 0
}
]
The model:
export class Post {
public _id: string;
public token: string;
public lat: string;
public lng: string;
}
Service class:
#Injectable({ providedIn: 'root' })
export class PostsService {
public posts: Post[] = [];
private postsUpdated = new Subject<Post[]>();
Post: Promise<any>;
constructor(private http: HttpClient) {}
private url: string = 'http://localhost:8000/location';
getPosts() {
this.http
.get<{ posts: any[] }>(this.url)
.pipe(
map((postData) => {
return postData.posts.map((post) => {
console.log(this.posts);
return {
_id: post._id,
token: post.token,
lat: post.lat,
lng: post.lng,
};
});
})
)
.subscribe((transformedPosts) => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]);
});
}
getPostUpdateListener() {
return this.postsUpdated.asObservable();
}
}
post-list.component.ts:
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
})
export class PostListComponent implements OnInit, OnDestroy {
posts: Post[] = [];
private postsSub: Subscription;
result: any;
constructor(public postsService: PostsService) {
//dependency-injection
}
ngOnInit() {
this.postsService.getPosts();
this.postsSub = this.postsService
.getPostUpdateListener()
.subscribe((posts: Post[]) => {
this.posts = posts;
});
}
onShow() {
console.log('TODO');
}
ngOnDestroy() {
this.postsSub.unsubscribe();
}
}
post-list.component.html:
<mat-accordion multi="true" *ngIf="posts.length > 0">
<mat-expansion-panel *ngFor="let post of posts">
<mat-expansion-panel-header>
{{ post.token }}
</mat-expansion-panel-header>
<p>{{ post.lat }}</p>
<p>{{ post.lng }}</p>
<mat-action-row>
<button mat-raised-button color="accent" (click)="onShow(post._id)">
SHOW
</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf="posts.length <= 0">No posts added yet</p>
app.component.html:
<app-header></app-header> <br /><br />
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
<br /><br />
<app-post-list></app-post-list>
And here's my result (photo):
I also tried to do it in different ways, always getting no result.
Any help or ideas would be much appreciated!
The error in the image says posts attribute does not exists on postData object which is gotten by get request. Absence of posts attribute is also clear in the JSON you provided.
{
"location": [
{
"_id": "5f3567a8d8e66b41d4bdfe5f",
"lat": "44.4363228",
"lng": "25.9912305",
"token": "edb153fb9d8d5628",
"__v": 0
}
]
You should completely remove the pipe and it should be fine.

How to access ReactQuill Ref when using dynamic import in NextJS?

I'm running into a funny problem. I'm using NextJS for its server-side rendering capabilities and am using ReactQuill as my rich-text editor. To get around ReactQuill's tie to the DOM, I'm dynamically importing it. However, that presents another problem which is that when I try to attach a ref to the ReactQuill component, it's treated as a loadable component instead of the ReactQuill component. I need the ref in order to customize how images are handled when uploaded into the rich-text editor. Right now, the ref returns current:null instead of the function I can use .getEditor() on to customize image handling.
Anybody have any thoughts on how I can address this? I tried ref-forwarding, but it's still applying refs to a loadable component, instead of the React-Quill one. Here's a snapshot of my code.
const ReactQuill = dynamic(import('react-quill'), { ssr: false, loading: () => <p>Loading ...</p> }
);
const ForwardedRefComponent = React.forwardRef((props, ref) => {return (
<ReactQuill {...props} forwardedRef={(el) => {ref = el;}} />
)})
class Create extends Component {
constructor() {
super();
this.reactQuillRef = React.createRef();
}
imageHandler = () => {
console.log(this.reactQuillRef); //this returns current:null, can't use getEditor() on it.
}
render() {
const modules = {
toolbar: {
container: [[{ 'header': [ 2, 3, false] }],
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }],
['link', 'image'],
[{ 'indent': '-1'}, { 'indent': '+1' }],
[{ 'align': [] }],
['blockquote', 'code-block'],],
handlers: {
'image': this.imageHandler
}
}
};
return(
<ForwardedRefComponent
value={this.state.text}
onChange={this.handleChange}
modules={modules}
ref={this.reactQuillRef}/> //this.reactQuillRef is returning current:null instead of the ReactQuill function for me to use .getEditor() on
)
}
}
const mapStateToProps = state => ({
tutorial: state.tutorial,
});
export default connect(
mapStateToProps, {createTutorial}
)(Create);
I share my solution with hope that it helps you too.
Helped from https://github.com/zenoamaro/react-quill/issues/642#issuecomment-717661518
const ReactQuill = dynamic(
async () => {
const { default: RQ } = await import("react-quill");
return ({ forwardedRef, ...props }) => <RQ ref={forwardedRef} {...props} />;
},
{
ssr: false
}
);
export default function QuillWrapper() {
const quillRef = React.useRef(false)
return <>
<ReactQuill forwardedRef={quillRef} />
</>
}
for example you can use the ref to upload image with custom hanlder
import React, { useMemo } from "react";
import dynamic from "next/dynamic";
const ReactQuill = dynamic(
async () => {
const { default: RQ } = await import("react-quill");
return ({ forwardedRef, ...props }) => <RQ ref={forwardedRef} {...props} />;
},
{
ssr: false,
}
);
export default function QuillWrapper({ value, onChange, ...props }) {
const quillRef = React.useRef(false);
// Custom image upload handler
function imgHandler() {
// from https://github.com/quilljs/quill/issues/1089#issuecomment-318066471
const quill = quillRef.current.getEditor();
let fileInput = quill.root.querySelector("input.ql-image[type=file]");
// to prevent duplicate initialization I guess
if (fileInput === null) {
fileInput = document.createElement("input");
fileInput.setAttribute("type", "file");
fileInput.setAttribute(
"accept",
"image/png, image/gif, image/jpeg, image/bmp, image/x-icon"
);
fileInput.classList.add("ql-image");
fileInput.addEventListener("change", () => {
const files = fileInput.files;
const range = quill.getSelection(true);
if (!files || !files.length) {
console.log("No files selected");
return;
}
const formData = new FormData();
formData.append("file", files[0]);
formData.append("uid", uid);
formData.append("img_type", "detail");
quill.enable(false);
console.log(files[0]);
axios
.post("the/url/for/handle/uploading", formData)
.then((response) => {
// after uploading succeed add img tag in the editor.
// for detail visit https://quilljs.com/docs/api/#editor
quill.enable(true);
quill.insertEmbed(range.index, "image", response.data.url);
quill.setSelection(range.index + 1);
fileInput.value = "";
})
.catch((error) => {
console.log("quill image upload failed");
console.log(error);
quill.enable(true);
});
});
quill.root.appendChild(fileInput);
}
fileInput.click();
}
I don't know much about useMemo
but if i don't use the hook,
the editor keeps rerendered resulting in losing focus and I guess perfomance trouble too.
const modules = useMemo(
() => ({
toolbar: {
container: [
[{ font: [] }],
[{ size: ["small", false, "large", "huge"] }], // custom dropdown
["bold", "italic", "underline", "strike"], // toggled buttons
[{ color: [] }, { background: [] }], // dropdown with defaults from theme
[{ script: "sub" }, { script: "super" }], // superscript/subscript
[{ header: 1 }, { header: 2 }], // custom button values
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }], // outdent/indent
[{ direction: "rtl" }], // text direction
[{ align: [] }],
["link", "image"],
["clean"], // remove formatting button
],
handlers: { image: imgHandler }, // Custom image handler
},
}),
[]
);
return (
<ReactQuill
forwardedRef={quillRef}
modules={modules}
value={value}
onChange={onChange}
{...props}
/>
);
}
In NextJS, React.useRef or React.createRef do not work with dynamic import.
You should Replace
const ReactQuill = dynamic(import('react-quill'), { ssr: false, loading: () => <p>Loading ...</p> }
);
with
import ReactQuill from 'react-quill';
and render after when window is loaded.
import ReactQuill from 'react-quill';
class Create extends Component {
constructor() {
super();
this.reactQuillRef = React.createRef();
this.state = {isWindowLoaded: false};
}
componentDidMount() {
this.setState({...this.state, isWindowLoaded: true});
}
.........
.........
render(){
return (
<div>
{this.isWindowLoaded && <ReactQuil {...this.props}/>}
</div>
)
}
}
Use onChange and pass all the arguments, here one example to use the editor.getHTML()
import React, { Component } from 'react'
import dynamic from 'next/dynamic'
import { render } from 'react-dom'
const QuillNoSSRWrapper = dynamic(import('react-quill'), {
ssr: false,
loading: () => <p>Loading ...</p>,
})
const modules = {
toolbar: [
[{ header: '1' }, { header: '2' }, { font: [] }],
[{ size: [] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[
{ list: 'ordered' },
{ list: 'bullet' },
{ indent: '-1' },
{ indent: '+1' },
],
['link', 'image', 'video'],
['clean'],
],
clipboard: {
// toggle to add extra line breaks when pasting HTML:
matchVisual: false,
},
}
/*
* Quill editor formats
* See https://quilljs.com/docs/formats/
*/
const formats = [
'header',
'font',
'size',
'bold',
'italic',
'underline',
'strike',
'blockquote',
'list',
'bullet',
'indent',
'link',
'image',
'video',
]
class BlogEditor extends Component {
constructor(props) {
super(props)
this.state = { value: null } // You can also pass a Quill Delta here
this.handleChange = this.handleChange.bind(this)
this.editor = React.createRef()
}
handleChange = (content, delta, source, editor) => {
this.setState({ value: editor.getHTML() })
}
render() {
return (
<>
<div dangerouslySetInnerHTML={{ __html: this.state.value }} />
<QuillNoSSRWrapper ref={this.editor} onChange={this.handleChange} modules={modules} formats={formats} theme="snow" />
<QuillNoSSRWrapper value={this.state.value} modules={modules} formats={formats} theme="snow" />
</>
)
}
}
export default BlogEditor
If you want to use ref in Next.js with dynamic import
you can use React.forwardRef API
more info

How to set prop data for chart.js in React?

I'm trying to fetch data from a SQL-database and show that data on a chart.js, but I'm getting this error:
Warning: Failed prop type: Invalid prop data supplied to ChartComponent.
My code looks like this:
import React, {Component} from 'react';
import {Line} from 'react-chartjs-2';
class MinData extends Component{
constructor(){
super();
this.state = {
data: {
labels: [],
datasets: []
}
};
}
componentDidMount(){
fetch('http://localhost:4000/api/myData?limit=6')
.then (results =>{
return results.json();
}).then(data => {
let receivedData = data.map((datapost) => {
return(
{
data: {
labels: datapost.timestamp,
datasets: datapost.temp_0
}
}
)
})
this.setState({data: receivedData}, function(){
console.log(this.state.data);
});
})
}
render(){
return(
<div className="enContainer">
<Line
data={this.state.data}
options={{
title:{
display: true,
text: 'Fladan mätpunkt',
fontSize: 25
}
}}
/>
</div>
)
}
}
export default MinData;
The idea is to set state of data with the fetched data.
I'm running out of ideas, but I guess there's something wrong with the way I return data from my map function.
UPDATE:
This is what I receive in Postman when doing the same request with limit set to receive two objects:
[
{
"timestamp": "2019-01-17T18:14:20.000Z",
"battery": 5.094,
"temp_0": 23.375,
"temp_10": 19.125,
"temp_20": 19,
"temp_30": 18.812,
"temp_40": 18.562,
"temp_50": 18.625,
"temp_60": 18.688,
"temp_70": 18.688,
"temp_80": 18.188,
"temp_90": 19,
"temp_100": 18.75,
"temp_110": 18.625,
"temp_120": 18.5
},
{
"timestamp": "2019-01-17T18:17:25.000Z",
"battery": 5.104,
"temp_0": 23.375,
"temp_10": 19.125,
"temp_20": 19,
"temp_30": 18.812,
"temp_40": 18.562,
"temp_50": 18.688,
"temp_60": 18.75,
"temp_70": 18.688,
"temp_80": 18.188,
"temp_90": 19,
"temp_100": 18.75,
"temp_110": 18.625,
"temp_120": 18.5
}
]
You need to check if data is present in this.state.data.labels before calling Line component. Render method would have run before componentDidMount gets a chance to return and call api therefore empty data is passed and passed to Line component.
{
this.state.data.labels.length && <Line
data={this.state.data}
options={{
title: {
display: true,
text: 'Fladan mätpunkt',
fontSize: 25
}
}}
/>
}
State data should have following structure:
{
labels: ['First', 'Second'],
datasets: [
{
label: 'My First dataset',
data: [65, 59, 80, 81, 56, 55, 40],
},
{
label: 'My Second dataset',
data: [28, 48, 40, 19, 86, 27, 90],
},
]
}

Use ng-multiselect-dropdown in a component instead of app.module.ts

I am trying to use the ng-multiselect-dropdown component in another component/page (viz. registered through RouterModule.forRoot in app.mudule.ts).
I have imported it in my component as suggested in this link-
import { Component, OnInit, NgModule, NO_ERRORS_SCHEMA } from
'#angular/core';
import { NgMultiSelectDropDownModule } from 'ng-multiselect-dropdown';
import { FormsModule } from '#angular/forms';
#Component({
selector: "ng-multiselect-dropdown",
templateUrl: "./multiselect.component.html"
})
#NgModule({
imports: [
NgMultiSelectDropDownModule.forRoot(),
FormsModule
],
schemas: [NO_ERRORS_SCHEMA]
})
export class MultiSelectComponent implements OnInit {
//constructor(private activatedRoute: ActivatedRoute,
// private router: Router,
// private http: HttpClient,
// #Inject('BASE_URL') private baseUrl: string) {}
dropdownList = [];
selectedItems = [];
dropdownSettings = {};
ngOnInit() {
this.dropdownList = [
{ item_id: 1, item_text: 'Mumbai' },
{ item_id: 2, item_text: 'Bangaluru' },
{ item_id: 3, item_text: 'Pune' },
{ item_id: 4, item_text: 'Navsari' },
{ item_id: 5, item_text: 'New Delhi' }
];
this.selectedItems = [
{ item_id: 3, item_text: 'Pune' },
{ item_id: 4, item_text: 'Navsari' }
];
this.dropdownSettings = {
singleSelection: false,
idField: 'item_id',
textField: 'item_text',
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
itemsShowLimit: 3,
allowSearchFilter: true
};
}
onItemSelect(item: any) {
console.log(item);
}
onSelectAll(items: any) {
console.log(items);
}
}
But I get the following errors, when I look in the browser developer tools.
emplate parse errors:
Can't bind to 'placeholder' since it isn't a known property of 'ng-multiselect-dropdown'.
1. If 'placeholder' is an Angular directive, then add 'CommonModule' to the '#NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '#NgModule.schemas' of this component.
Can't bind to 'data' since it isn't a known property of 'ng-multiselect-dropdown'.
Can't bind to 'settings' since it isn't a known property of 'ng-multiselect-dropdown'.
The html of the page is as below -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<ng-multiselect-dropdown [placeholder]="'custom placeholder'"
[data]="dropdownList"
[(ngModel)]="selectedItems"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)">
</ng-multiselect-dropdown>
</body>
</html>
This error means that the component's module doesn't have the required imports.
Try importing the module in this components' module file.
Instead of
[placeholder]="'custom placeholder'"
use
[value]="custom placeholder"
And of course check that the import in the module It's done the correct way
However I checked the official documentation and you can bind the placeholder property
Finally got it to work. The NgMultiSelectDropDownModule module itself should be imorted to app.module.ts. The ngOnInit() method should be used inside the component.ts. As correctly pointed out by others, the component's own selector should be different from the ng-multiselect-dropdown selector used in the component html.

Realm-js: Cannot access realm that has been closed

Realm keeps throwing this error in a simple use case:
Cannot access realm that has been closed
My files:
RealmExample.js
import Realm from 'realm';
class Item {}
Item.schema = {
name: 'Item',
properties: {
name: 'string',
date: 'date',
id: 'string'
},
};
export default new Realm({schema: [Item]});
app.js
//My imports
export default class App extends Component<{}> {
render() {
return (
<RealmProvider realm={realm}>
<ConnectedExample />
</RealmProvider>
);
}
}
ConnectedExample.js
import React, { Component } from 'react';
import {
Text,
ScrollView,
TouchableOpacity,
View,
StyleSheet,
} from 'react-native';
import uuid from 'uuid';
import { connectRealm } from 'react-native-realm';
import ConnectedExampleItem from './ConnectedExampleItem';
const styles = StyleSheet.create({
screen: {
paddingTop: 20,
paddingHorizontal: 10,
backgroundColor: '#2a2a2a',
flex: 1,
},
add: {
height: 44,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 10,
backgroundColor: '#1a1a1a',
},
addText: {
color: 'white',
},
});
class ConnectedExample extends Component {
count = 0;
onPressAddItem = () => {
const { realm } = this.props;
realm.write(() => {
realm.create('Item', {
name: this.count.toString(),
date: new Date(),
id: uuid.v4(),
});
this.count++;
});
};
render() {
return (
<View style={styles.screen}>
<TouchableOpacity onPress={this.onPressAddItem} style={styles.add}>
<Text style={styles.addText}>Add Item</Text>
</TouchableOpacity>
<ScrollView>
{this.props.items.map((item) => (
<View key={item.id}>
<ConnectedExampleItem id={item.id} />
</View>
))}
</ScrollView>
</View>
);
}
}
export default connectRealm(ConnectedExample, {
schemas: ['Item'],
mapToProps(results, realm) {
return {
realm,
items: results.items.sorted('date') || [],
};
},
});
ConnectedExampleItem.js
import React, {
Component,
PropTypes,
} from 'react';
import {
StyleSheet,
TouchableOpacity,
Text,
} from 'react-native';
import { connectRealm } from 'react-native-realm';
const styles = StyleSheet.create({
item: {
height: 44,
justifyContent: 'center',
paddingHorizontal: 10,
marginTop: 10,
backgroundColor: 'cyan',
},
});
class ConnectedExampleItem extends Component {
onPressRemoveItem = (item) => {
const { realm } = this.props;
realm.write(() => {
realm.delete(item);
});
};
render() {
return (
<TouchableOpacity
onPress={() => this.onPressRemoveItem(this.props.item)}
style={styles.item}
>
<Text>{this.props.item.name}</Text>
</TouchableOpacity>
);
}
}
export default connectRealm(ConnectedExampleItem, {
schemas: ['Item'],
mapToProps(results, realm, ownProps) {
return {
realm,
item: results.items.find(item => item.id === ownProps.id),
};
},
});
The strange thing is that when running this code on my project I run into the Cannot access realm that has been closed (I haven't instantiated Realm anywhere else), however, if I run the example in the react-native-realm repo, it runs fine.
Also, the introduction example on the Realm documentation page runs fine as well.
What could be the issue?
Thank you.
PS: Running on React-native 0.51, Android device 6.0.

Resources