Well, I have been reading, and I can't find a solution for this. I'm starting with this project. I want to know how to use a service with GET method like this https://api.myjson.com/bins/1axhir and use it in my menu. This is how my code is written. I'm using a template NGX-ADMIN but they don't have any documentation.
page.components.ts
import { Component } from '#angular/core';
import { MENU_ITEMS } from './pages-menu';
#Component({
selector: 'ngx-pages',
template: `
<ngx-sample-layout>
<nb-menu [items]="menu"></nb-menu>
<router-outlet></router-outlet>
</ngx-sample-layout>
`,
})
export class PagesComponent {
menu = MENU_ITEMS;
}
pages-menu.ts
import { NbMenuItem } from '#nebular/theme';
export const MENU_ITEMS: NbMenuItem[] = [
{
title: 'Dashboard',
icon: 'nb-home',
link: '/pages/dashboard',
home: true,
},
{
title: 'CONFIGURACIONES',
group: true,
},
{
title: 'Usuarios',
icon: 'nb-keypad',
link: '/pages/ui-features',
children: [
{
title: 'Buttons',
link: '/pages/ui-features/buttons',
},
],
},
];
I want to use a web service like, this example https://api.myjson.com/bins/1axhir, instead of the Constant Array give me a hand please. TY
Angular is only used for FrontEnd and for making API you need to use Node.js or any other Backend framework.
if you want i can give you the node.js code for the same.
Also for integrating the API in angular application, you need to use observeables and subscribers
Related
I am creating a web app in ReactJS and I am trying to call an API from within my Chart class.
I have a program that takes data from a ML model and writes it to an API in the form of an array. I'm new to using ReactJS and I just want to make a call to the API to return the array into my data variable in react to render in the graph onscreen.
The data in the API is formatted as ..
[
1,
2,
3,
4
]
Currently I have the data hard coded into a separate file and am importing that but I want it to be called from the API directly so it updates.
import React, {Component} from "react"
import {Line} from "react-chartjs-2"
import {popuData, dayLabels} from "./FakeGraphData";
class PlanGraph extends Component{
constructor(props){
super(props);
this.state = {
chartData:{
labels: dayLabels,
datasets: [
{
label:'Predicted Park Crowds',
data: popuData,
borderColor: 'rgba(77, 112, 255, 1)',
backgroundColor: 'rgba(77, 112, 255, 1)'
}
]
}
}
}
render(){
return(
<div className = "chart">
<Line
data={this.state.chartData}
options={{
title: {
display:true,
text:"Predicted Park Crowds",
fontSize:25
},
legend:{
display: true,
position: 'right'
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Anticipated Crowds'
},
ticks: {
beginAtZero: true
}
}],
xAxes: [{
scaleLabel: {
display:true,
labelString: 'Days in the future'
}
}]
}
}}
/>
</div>
)
}
}
export default PlanGraph
Add a container Component & use Props
The component you've shown us here looks like a presentational component (has html structure, cares about how things look). What you should do is create a container component, these components care about things like logic & getting data. You can read about this design methodology here.
The container will render the component you have posted above but will pass some props kind of like this.
Example
class PlanGraphContainer extends Component {
state = {
dataToPass: []
};
async componentDidMount() {
const response = await fetch('https://your-api-request');
const data = await response.json(); // maybe you need this, you have to check your response
this.setState({dataToPass: data});
}
render() {
return <PlanGraph data={this.state.dataToPass} />
}
}
Then inside your PlanGraph use this.props.data to see the data that is being passed. make sure you have some fake data or loading state whilst you wait for the request to be complete. our you can add something like this
render() {
const { dataToPass } = this.state;
return (dataToPass && dataToPass.length)
? <PlanGraph data={this.state.dataToPass} />
: null;
}
I'm using Laravel 5.4, vue.js 2.3 and vue-router.
Current situation
When example.com is hit, Laravel returns the app view which starts the Vue.app
web.php
Route::get('/', function () {
return view('app');
});
app.js
const routes = [
{ path: '/', component: App },
];
const app = new Vue({
el: '#app',
router,
data () {
return {}
},
});
App.vue
export default {
...
}
What I'm trying to do
If usa.example.com is typed, I would like the alert() in my App.vue to show usa.
If italy.example.com is typed, I would like the alert() in my App.vue to show italy.
I read the documentation of vue-router but I'm not sure wether it is a Laravel issue, a Vue issue or both.
App.vue
export default {
....
created() {
alert('subdomain is ' + $route.params.subdomain)
}
}
VueRouter doesn't keep track of the subdomain.
But, you can get the subdomain from the location and use that in your component's created method:
created() {
let subdomain = location.hostname.split('.').shift();
alert('subdomain is ' + subdomain);
}
The above code is based off of this answer.
So I'm trying to create a VueJS application, and I was given a set of JSON objects that are retrievable through a .json endpoint.
I'll call them People. So I get an array of people in this.people after using VueResource.
I'm able to iterate and get all the name displayed on the side, however, since its not an API nor has unique IDs minus their array indexes, I am having trouble trying to narrow down each object and create a single Person view page.
Hence if it was a normal api, I could do '/people/:id', but I can't. I'm also wondering if I may have stored the Prop/Component correctly.
I put together a quick example of how this might work with the Star Wars API.
const Loading = {
template: `<h1>Loading...</h1>`
};
const People = {
props: ["people"],
template: `
<div>
<h1>People</h1>
<ul>
<li v-for="person in people">
<router-link :to='{name: "person", params:{person: person}}'>{{person.name}}</router-link>
</li>
</ul>
</div>
`
};
const PersonDetails = {
props: ["person"],
template: `
<div>
<h1>{{person.name}}</h1>
<div>Height: {{person.height}}</div>
<div>Mass: {{person.mass}}</div>
<div>Hair Color: {{person.hair_color}}</div>
<br/>
<router-link to="people">Back to people</router-link>
</div>
`
};
const routes = [
{ path:"/", component: Loading},
{ path: "/people", name: "people", component: People},
{ path: "/person", name: "person", component: PersonDetails, props: true},
]
const router = new VueRouter({
routes
})
new Vue({
el: "#app",
router,
data:{
people:[]
},
mounted(){
this.$axios.get("https://swapi.co/api/people/")
.then((response) => {
this.people = response.data.results
this.$router.push("people")
})
}
});
Here is the working example.
I'm trying to write a pipe that filters an array of JSON objects. Every object has 3 keys that are booleans - demo, github, finished and I want to be able to input these into my filter, and present only the objects where the key is true. I don't need to input multiple values, a single string (key) is enough.
So far, no matter what I input into the filter, the page shows no data. If I remove the filter completely I get everything defined in the service. There are also no error messages logged.
So I have a service that provides the pages:
import { Injectable } from 'angular2/core';
export class Page {
constructor(public img: string, public name: string, public repo: string, public description: string, public demo: boolean, public github: boolean, public finished: boolean) { }
}
#Injectable()
export class PagesService {
getPages() {
return [
new Page('./app/images/placeholder.png', 'veryNiceWords', 'https://github.com/Shooshte/veryNiceWords', 'A hobby app, made to enable posting, rating and sharing quotes over social networks. Work in progress.', false, true, false),
new Page('./app/images/placeholder.png', 'ZIC IJS', 'https://github.com/Shooshte/ZIC', 'Refurbishing of on old library webpage with AngularJS.', false, true, false),
new Page('./app/images/weather.png', 'Show the Local weather', 'http://codepen.io/shooshte/pen/NxOwOX', 'A freeCodeCamp exercise, designed to show the local weather.', true, false, true),
new Page('./app/images/calculator.png', 'Calculator', 'http://codepen.io/shooshte/pen/qbjJdy', 'A freeCodeCamp exercise, which requires you to build a javascript calculator.', true, false, true),
new Page('./app/images/github.png', 'MTGO Draft Replayer', 'https://github.com/Shooshte/MTGO-Draft-Replayer', 'A simple web app that opens a MTGO draft log file, and re-creates the draft from it.', false, true, false),
new Page('./app/images/codeeval.png', 'codeEval', 'https://github.com/Shooshte/CodeEval', 'CodeEval challenges solutions written in javascript and posted to gitHub.', false, true, true)
];
}
}
Here is where I call the service OnInit and define the pipe:
import { Component } from 'angular2/core';
import { ViewEncapsulation } from 'angular2/core';
import { Page, PagesService } from './pages.service';
import { Pipe, PipeTransform } from 'angular2/core';
#Pipe({ name: 'pagesFilter' })
export class pagesFilter {
transform(pages, [key]) {
return pages.filter(page => {
return page.key === true;
});
}
}
#Component({
selector: 'portfolio',
templateUrl: '/app/views/portfolio.html',
styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
pipes: [pagesFilter],
encapsulation: ViewEncapsulation.None
})
export class PortfolioComponent {
filter = 'everything';
pages: Page[];
constructor(private _pagesService: PagesService) { }
ngOnInit() {
this.pages = this._pagesService.getPages();
}
}
This is how I use the pipe in my html:
<div class="portfolioContainer">
<div class="displayHack"></div>
<div *ngFor="#p of pages | pagesFilter:demo" class="portfolioPageContainer">
<img [attr.src]="p.img" class="portfolioThumbnail">
<h2>{{ p.name }}</h2>
<a [attr.href]="p.repo">
<div>
<p>{{ p.description }}</p>
</div>
<p class="portfolioRepoLink">See the Code!</p>
</a>
</div>
<div class="displayHack"></div>
</div>
You could try this instead:
#Pipe({ name: 'pagesFilter' })
export class pagesFilter {
transform(pages, [key]) {
return pages.filter(page => {
return page[key] === true; // <------
});
}
}
In your case you try to access the property with name "key" but not with the name corresponding to the content of the key parameter.
Moreover if you want to use the value "demo" (not to evaluate the expression "demo"), you need to use the following:
<div *ngFor="#p of pages | pagesFilter:'demo'"
class="portfolioPageContainer">
I was wondering if it's possible to use "indexRedirect" in a route configuration object (so without using JSX).
I tried without success, so I assumed that this isn't supported at the moment, but then my issue (https://github.com/reactjs/react-router/issues/3150) was closed without comment, so I still don't know if it's because the feature is already there but I misuse it, or because this is a unwanted feature.
Thanks in advance. :)
As described in the docs, the equivalent to indexRedirect using a plain configuration object looks like this
const routes = [{
path: '/',
component: App,
indexRoute: { onEnter: (nextState, replace) => replace('/welcome') },
childRoutes: [
{ path: 'welcome', component: Welcome },
{ path: 'about', component: About }
]
}]
Using plain routes config it's a bit more low level API, and there is no point of having special redirect or indexRedirect keys in the routes object. Instead you could use onEnter to accomplish a redirect. Here is how:
import React from 'react'
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router'
const Home = () => <h3>Home</h3>
const About = () => <h3>About</h3>
const routes = [{
path: '/',
component: Home,
onEnter: (nextState, replace) => replace('/about')
}, {
path: '/about',
component: About
}]
render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
Edit: added this into docs as well.
I would appreciate the same thing as JGX: working relative paths for this kind of redirecting