AngularJS get certain parameters from $resource query request - javascript

I have object which I retrieved like this $scope.posts = posts.query()
posts is ngResrouce
angular.module('flapperNews')
.factory('posts', ['$resource', function($resource) {
return $resource('api/posts.json/:id', {id: "#id"})
}]);
Retrieved object
[
0: {
$hasKey: "object:4",
title: "some text",
content: "hello world there",
upvotes: 0
}
1: {
$hasKey: "object:5",
title: "Lorem ipsum is dolor",
content: "hello world there",
upvotes: 0
}
2: {
$hasKey: "object:6",
title: "When there is nothing to share",
content: "hello world there",
upvotes: 0
}
]
How can I get just "titles" from this retrieved object so I can use it for
AngularJS Formly validation? (validating if the new post title would be unique)

Related

Angular Changing/Replacing the value in a string based on the User selection

I am working on an offer letter template that will replace/modify Dynamic Data Points like Name, Address, Role, Salary, etc based on the candidate selected from a list of candidates. There is a fixed syntax for a dynamic data points i.e they will be enclosed within <<>>, for example :
Welcome to the family, <<Name>>
You will be paid <<Salary>> for the duration of your employment.
In other words, these few data points will change by selecting the candidate we want to offer the job and the rest of the template will remain the same. Here is a demo to help you understand.
This is a dummy array I have created with 1 template, In the real-world app, I can have many templates with different clauseNames, so I am looking for a permanent fix.
.ts file, Template List :
[{
templateId: 1,
templateName: "Offer",
clauses: [
{
clauseName: "Introduction",
clauseId: 1,
texts: [
{
text: "Hello <<Name>>, Welcome to the Machine",
textId: 1,
}]
},
{
clauseName: "Address",
clauseId: 2,
texts: [
{
text: "<<Address>>",
textId: 2,
}]
},
{
clauseName: "Date Of Joining",
clauseId: 3,
texts: [
{
text: "You can join us on <<DateOfJoining>>",
textId: 3,
}]
},
]
}]
and here is the candidate list,
candidateList = [
{ name: "Simba", address: "Some Random Cave" },
{ name: "Doe John", address: "line 4, binary avenue, Mobo" },
{ name: "B Rabbit", address: "8 mile road, Detroit" },
{ name: "Peter Griffin", address: "Spooner Street" },
{ name: "Speedy Gonzales", address: "401, hole 34, Slyvester Cat Road" },
{ name: "Morty", address: "Time Machine XYZ" },
{ name: "Brock", address: "pokeball 420, Medic center" },
]
You can use regular expressions to replace those placeholders such as:
var result = text.text.replace(/\<\<(.*?)\>\>/g, function(match, token) {
return candidate[token.toLowerCase()];
});
One way to incorporate this to your display is by creating a property that returns the formatted text.
I have updated your stackblitz here.
Take a look at this demo
I have modified the logic in below method:
showTeplate(name,address,doj) {
this.clauseList = [];
for (let a of this.templateList) {
if (a.clauses != null) {
for (let cl of a.clauses) {
const tempObj = JSON.parse(JSON.stringify(cl));
tempObj.texts.forEach(textObj => {
textObj.text = textObj.text.replace("<<Name>>",name);
textObj.text = textObj.text.replace("<<Address>>",address);
textObj.text = textObj.text.replace("<<DateOfJoining>>",doj);
})
this.clauseList.push(tempObj)
}
}
}
console.log("Clause list", this.clauseList)
}

Filter array by tag Vuejs

I'm currently working with vuejs and vuex. Here is my issue :
I have a store with all the data
state: {
articles: [{
title: "Article 1",
id: 1,
tag: "Tutorial"
}, {
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
}]
}
On the homepage, I want to display all kind of articles. On the tutorial page I only want to display articles with tag "tutorial", etc...
I'm using vue-router. I'm working with a computed property and a v-for so I can loop in the articles.
computed: {
articles() {
if (this.$route.meta.title == 'Tutorial') {
return this.$store.state.articles.tag == 'Tutorial'
}
if (this.$route.meta.title == 'Review') {
return this.$store.state.articles.tag == 'Review'
}
else if (this.$route.meta.title == 'Home') {
return this.$store.state.articles
}
}
}
I know that return this.$store.state.articles.tag == 'Tutorial' can't work, I'm looking for a way to code it correctly but I'm stuck!
Also, if you have a completely different and better way to do it, feel free to tell me!
Thank you for your time :)
As everybody mentioned you will need to use filter but as a pattern you should structure it with vuex getters
when you access properties from vuex state do not to access them directly but the correct thing is to use getters
Vuex store e.x.
const store = new Vuex.Store({
state: {
articles: [
{
title: "Article 1",
id: 1,
tag: "Tutorial"
},
{
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
]
},
getters: {
allArticles: state => {
return state.articles
},
tutorialArticles: state=>{
return state.articles.filter(article=>articles.tag=='Tutorial')
},
reviewArticles: state=>{
return state.articles.filter(articles=>articles.tag=='Review')
}
}
})
//end of vuex store
Then in your "all articles" component you use
computed:{
articles(){
return this.$store.getters.allArticles;
}
}
Then in your tutorial articles component you use
computed:{
articles(){
return this.$store.getters.tutorialArticles;
}
}
This is very important because if you need to change the code for the filter method you do it in one place and thats the purpose of using Vuex
Probably the best way is using .filter()
var obj = {state: {
articles: [{
title: "Article 1",
id: 1,
tag: "Tutorial"
}, {
title: "Article 2",
id: 2,
description: "Article 2",
tag: "Review"
}
]}}
var filtered = obj.state.articles.filter(o=>o.tag == "Tutorial");
console.log(filtered)

Angular - Get array from JSON file

Sorry for the noob question but I am just getting started with Angular. I have this array declared in services.js:
var articles = [{
id: 1,
title: 'Article 1 Title',
intro: 'Article 1 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 1 Text',
url: 'http://www.domain.com'
}, {
id: 2,
title: 'Article 2 Title',
intro: 'Article 2 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 2 Text',
url: 'http://www.domain.com'
}];
Now that everything works fine in my Angular App I want to read this array from a JSON file that can be found, for example, at www.domain.com/articles.json and it looks like this:
{
"articles": [
{
"id": 1,
"title": "Article 1",
"intro": "Article 1 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 1 Text",
"url": "http://www.domain.com/article-1"
},
{
"id": 2,
"title": "Article 2",
"intro": "Article 2 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 2 Text",
"url": "http://www.domain.com/article-2"
}
]
}
How can I make this change?
To get the data of the file in your Angular app, you'll have to get the file's contents through an HTTP request. The easiest way to do this is by using the $http service.
Example (with relative url):
$http.get('/articles.json').then(function (response) {
var articles = response.data.articles;
// Do something with articles...
});
The callback function you're passing to the then method will be called when the HTTP request was successful. Note that your data will only be available in this callback function. Also don't forget to include a dependency to the $http service in your controller. ;)

React get object inside another object

I got a simple json api and want to display some of objects fields with react.
The api has the following structure:
{"data" : [
0: Object
id: "1"
type: "Item"
attributes: Object
title: "lorem impsum"
body: "lorem ipsum"
1: Object
id: "2"
....
]}
And I'm trying to display attributes items(title, body)
The problem is that
this works fine and displays id
{items.map(item =>
<div>{item.id}</div>
)}
BUT
If I try to use {item.attributes.title} I receive
TypeError: Cannot read property 'title' of undefined
So item.attributes is undefined.
What's wrong here?
this is the most common error that occurs because you never know what object you are going to get from server, so it is always good way to check before accessing the data, so you can try
{item.attributes && item.attributes.title ? item.attributes.title : 'print something for missing title' }
//item.attributes && item.attributes.title means if both the values are present in Object
This should help you. I couldn't find an error in your program. So, I've created a working example to solve this.
const data = {
"data": [{
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}]
}
class Sample extends React.Component{
render() {
return <div>
{
data.data.map((el) => {
return <div>
<h1>{el.id}</h1>
<div>{el.attributes.title}</div>
<div>{el.attributes.body}</div>
</div>
})
}
</div>
}
}
ReactDOM.render(<Sample/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

could not read json data using jquery with for loop

I have a data object and inside that I have data object with json data inside. Here is how is looks like. the name of the file is data.js
var data =
[
{
title: 'this is title one',
commit: 'this is commit'
},
{
title: 'this is title two',
commit: 'this is commit'
},
{
title: 'this is title three',
commit: 'this is commit'
},
{
title: 'this is title four',
commit: 'this is commit'
},
{
title: 'this is title five',
commit: 'this is commit'
},
{
title: 'this is title six',
commit: 'this is commit'
},
{
title: 'this is title seven',
commit: 'this is commit'
}
]
here is my code
for (var i = 0; i < data.length; i++) {
$(container).load(view, function () {
console.log(data[i].title);
li.append('<img src="../images/profile.png" alt="Profile photo" />');
li.append('<span class="commit">' + data[i].title + '</span>');
li.append('<p>' + data.commit + '</p>');
li.append('<section class="clear"></section>');
$('#home ul').append(li);
});
}
Now I am getting this error in my console
Cannot read property 'title' of undefined
above error is on this line
li.append('<span class="commit">' + data[i].title + '</span>');
how to fix this?
Well, data.js is not really json.
First switch from load() to getJSON()
$.getJSON(view, function(data) { })
next remove the line
var data =
just have the json contents. jQuery will assign JSON to argument data.
Your json array contains errors.
You can validate your json here http://json.parser.online.fr/
Must be so:
{
"title": ["this is title one", "this is title two", "this is title three", "this is title four", "this is title five", "this is title six", "this is title seven" ]
,
"commit": [ "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit" ]
}

Categories

Resources