Angular 2 get json data from url - javascript

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let ep = './data.json';
this.events = this.http
.get(ep, { headers: headers })
.map(res => res.json())
.map(({results}: { results: Data[] }) => {
return results.map((data: Data) => {
return {
title: data.title,
start: new Date(data.from),
colors.yellow,
};
});
});
Here is my code in Angular 2. I want to get data from a JSON file and show it in the angular-calendar.
Here is angular-calendar Demo: How can I do that?

You can make a service that contains the data for the calendar.
getList(): any
{
var date = new Date( '2017-01-12' );
var date2 = new Date( '2017-03-17' );
return (
[
{ title: 'Beauty And The Beast', start: date2, color: { primary: '#e3bc08', secondary: '#FDF1BA' } },
{ title: 'La La Land', start: date, color: { primary: '#e3bc08', secondary: '#FDF1BA' } }
]
)
}
Then you will have to remove the async pipe from the template.
Before:
[events]="(events | async ) || []
After:
[events]="(events) || []
Then call the service in the component:
fetchEvents()
{
this.events= this._data_Service.getList()
}
2. To get data.json file with Http you need to put the JSON file in the assets folder: ./assets/data.jsom, so that it can be accessed by the application: localhost:8080/data.json.
Then you simply make a get request.
fetchEvents(): void {
this.events = this.http
.get('../../assets/data.json') // the path may vary depending
// on your directory structure.
.map(res => res.json())
.map((results) => { // this might be different depending on
// your json and type definition.
return results.map((data: Data) => {
console.log({title: data.title,
start: new Date(data.from),
color: colors.yellow})
return {
title: data.title,
start: new Date(data.from),
color: colors.yellow,data
};
});
});
}// fetchEvents
Here is the JSON I used:
[
{"title":"La La Land","from":1490475722305},
{"title":"Beauty And The Beast","from":1490475722305}
]
finally, you can include the type definition in your component:
interface Data {
title: string;
from:string;
}
interface DataEvent extends CalendarEvent {
data: Data;
}

Related

apollo client offsetLimitPagination not working

I have a hook..
export function useLazyProposalList() {
const [getQueueData, { loading, data, error, fetchMore }] = useLazyQuery(PROPOSAL_LIST, {
fetchPolicy: 'no-cache',
});
const proposalList = React.useMemo(() => {
if (!data) {
return null;
}
return transformProposals(data);
}, [data]);
return {
getQueueData,
fetchMore,
loading,
data: proposalList,
error,
};
}
In the component
const {
getQueueData,
data: queueData,
fetchMore: fetchMoreProposals,
// loadMore: loadMore,
} = useLazyProposalList();
If user clicks on fetch more button, I call: fetchMoreProposals .
await fetchMoreProposals({
variables: {
offset: visibleProposalList.length,
},
});
but this doesn't update my data. I read that we should use offsetLimitPagination, but my data from query is not array itself. It's like this: queue { id: '1', items:[] } and because of this, offsetLimitPagination doesn't work. So I tried merge
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
queue: {
keyArgs: false,
merge(existing, incoming) {
console.log(existing, incoming);
if (!incoming) return existing;
if (!existing) return incoming;
},
},
},
},
}
but in the console, it just prints refs instead of real data.
What could be the issue ?

VueJS fetch promises

I have a component:
Vue.component('mail-list', {
props: ['userInbox'],
template:
`
<div>
<p>{{userInbox}}</p>
</div>
`
});
I want to print in p tag props content which is the result of created function
let options = {
el: "#app",
data: {
pollingId: null,
},
created: function() {
let users = fetch('/inbox')
.then(response => response.json())
.then(aJson => {return (aJson)})
this.userInbox = users
}
}
let vm = new Vue(options);
But this is only returning a promise which I can not work with.
PromiseĀ {<pending>}
Promise has this content:
{ '1':
Mail {
id: 1,
from: 'pep#mydomain.com',
to: 'mar#mydomain.com',
subject: 'Hi Mar',
body: 'This is a test from pep to mar',
timestamp: 1590647288599 },
'6':
Mail {
id: 6,
from: 'nil#mydomain.com',
to: 'mar#mydomain.com',
subject: 'By Mar',
body: 'This is a test from nil to mar',
timestamp: 1590647288599 } }
I have to display in p tag the from and subject attributes of each.
First, don't forget to register userInbox in your data.
Second, assign it in promise callback
let options = {
el: "#app",
data: {
pollingId: null,
userInbox: ''
},
created: function() {
let users = fetch('/inbox')
.then(response => response.json())
.then(aJson => {
this.userInbox = aJson
})
}
}
let vm = new Vue(options);

How to push new data input to top on the list

hello how to push new data to the top list using vue.js and laravel, I tried but still failed, I hope someone can help with the problem.
this is my Controller
public function addComment()
{
$this->validate(request(), [
'comment' => 'required',
]);
$comment = [
'comment' => request()->comment,
'article_id' => request()->article_id,
'user_cid' => Auth::user()->user_cid,
];
$comment = ArticleComment::create($comment);
return new ArticleCommentResource($comment);
}
and this is my Vue.js Method
data() {
return {
data: [],
comments:[],
form: new Form({
comment: '',
article_id: this.articleid,
})
}
},
methods: {
onSubmit() {
this.showLoader = true
this.form.post('add-comment')
.then(response => {
console.log(response.article_id);
this.form.article_id = response.article_id;
});
},
}
how to handle it, thank you
I hope someone can help
Assuming your list simply loops through your comments array, you need to push the response at the first position of the list:
onSubmit() {
this.showLoader = true
this.form.post('add-comment')
.then(response => {
this.comments.unshift(response);
});
},
This assumes that response is the actual comment (I can't see into your form class).
<script>
import Form from 'form-backend-validation';
export default {
data:() => ({
form: new Form({
article_id: null,
}),
}),
mounted() {
this.fetch();
},
methods: {
async fetch() {
const response = await this.form.post('add-comment');
this.form.article_id = response.comment.article_id;
}
}
}
</script>
Please try this one.

Zapier JS conditional statement

I'm noob at JS, trying to write an APP for zapier. I have a test auth function that I can't get to fail when bad info is sent in.
Here is the test function:
require('should');
const zapier = require('zapier-platform-core');
const App = require('../../index');
const appTester = zapier.createAppTester(App);
describe('Triggers - Get Groups', () => {
zapier.tools.env.inject();
it('should get an array', done => {
const bundle = {
authData: { api_key: process.env.API_KEY },
inputData: {}
};
appTester(App.triggers['getgroup'].operation.perform, bundle)
.then(results => {
results.includes('id');
done();
})
.catch(results);
});
});
If successfull, a sample return should look like this:
{"id":1815,"name":"New Contacts","count":2}
A failure looks like this:
{"RESPONSE":"FAIL","REASON":"Invalid API key"}
Here is the getgroup function:
// Trigger stub created by 'zapier convert'. This is just a stub - you will need to edit!
const { replaceVars } = require('../utils');
const getList = (z, bundle) => {
let url = 'https://path.to/apisite?action=getGroups&apiKey={{api_key}}';
url = replaceVars(url, bundle);
const responsePromise = z.request({ url });
return responsePromise.then(response => {
response.throwForStatus();
return z.JSON.parse(response.content);
});
};
module.exports = {
key: 'getgroup',
noun: 'Getgroup',
display: {
label: 'Get Groups',
description: 'Triggers when loaded to pull groups.',
hidden: true,
important: false
},
operation: {
inputFields: [
{
key: 'group',
label: 'Groupget',
type: 'string',
required: false
}
],
outputFields: [
{
key: 'count',
type: 'string'
},
{
key: 'id',
type: 'string',
label: 'groupid'
},
{
key: 'name',
type: 'string',
label: 'groupname'
}
],
perform: getList,
sample: { count: 243, id: 27806, name: 'New Contacts' }
}
};
When I test auth on Zapier's website, I'd like auth to fail, and return the "REASON"
How do I do this?

Return object from observable inside another observable

I try to fetch data from 3 different REST end points. The data model consists of main data and has advanced Array with 2(might be more in the future) Objects. I want to inject an Array with options into each of advanced Objects, based on REST endpoint specified in each of them. Everything works and is returned from Observable as Object, except appended options, that come as Observables.
Simplified data:
{
simple: {
param: "searchQuery",
},
advanced: [
{
param: "food",
optionsModel: {
url: "http://address.com/food",
}
},
{
param: "drinks",
optionsModel: {
url: "http://address.com/drinks",
}
}
]
}
food and drinks have the same structure consisting of Objects with name and id:
{
data: [
{
name: "DR1",
id: 1
},
{
name: "DR2",
id: 1
},
...
]
}
In my data model I don't have options[] array, so I inject it manually. Service:
searchConfiguration$: Observable<SearchConfiguration> = this.http
.get(this._configURL)
.map((config) => {
let configuration = config.json();
let advancedArray = configuration.advanced;
if(advancedArray) {
advancedArray.forEach(advanced => {
advanced.options = [];
advanced.options = this.http.get(advanced.optionsModel.url)
.map((r: Response) => r.json().data
})
}
return configuration;
})
Parent component:
getSearchConfig() {
this.searchConfiguration$ = this._bundlesService.searchConfiguration$;
}
Then I have async pipe in the html to subscribe to Observable. How can I get my options appended to advanced as actual Arrays and not as a stream?
Edit - Solution
Thanks to martin's answer, the solution is to flatten both streams and connect them in the end with forkJoin()
searchConfiguration$: Observable<SearchConfiguration> = this.http
.get(this._configURL)
.map((config) => config.json())
.concatMap((configuration) => {
let observables = configuration.advanced.map((advanced) => {
return this.http.get(advanced.optionsModel.url)
.map((r: Response) => r.json().data)
.concatMap((options) => advanced.options = options)
});
return Observable.forkJoin(observables, (...options) => {
return configuration;
})
});
I didn't test it but I think you could you something as follows:
searchConfiguration$: Observable<SearchConfiguration> = this.http
.get(this._configURL)
.map((config) => config.json())
.concatMap(configuration => {
var observables = configuration.advanced.map(advanced => {
return this.http.get(advanced.optionsModel.url)
.map((r: Response) => r.json().data);
});
return Observable.forkJoin(observables, (...options) => {
configuration.options = options;
return configuration;
});
})

Categories

Resources