Angular get parameter from JSON rootscope object - json

in angular I have a rootscope object like this:
{"id":12,"email":"testmail#test.com","given_name":"John","family_name":"Doe","car":"BMW"}
How can I acces each parameter individually?
Now I just do
{{ currentUser }}
And doing
{{ currentUser.email }}
obviously doesn't work. I'm guessing something is wrong with this JSON object?
Thank you

There is anything wrong with your json object, check this way to set data on the rootScope. Maybe is helpful for you.
angular.module('app', [])
.factory('currentUser', [
function () {
return {
"id": 12,
"email": "testmail#test.com",
"given_name": "John",
"family_name": "Doe",
"car": "BMW"
};
}])
.run([
'$rootScope', 'currentUser', function ($rootScope, currentUser) {
$rootScope.currentUser = currentUser;
}
]);
then later you can call {{ currentUser.email }} on templates and $scope.currentUser.email on code.
you can update the data on the controllers injecting $rootScope.

Related

Include additional data/value in Vuejs v-for loop

I'm trying to include external data/value into a v-for loop in VueJS. Have no idea how to go about it. Basically I have data/value in value as follows:
External Data
{{ time.one }}
{{ time.two }}
NOTE: I am receiving the data exactly as above as its coming from an API
JSON (own data)
{
"persons": [
{
"title": "Prof",
"name": "SomeProf"
},
{
"title": "Dr",
"name": "SomeDr"
},
]
}
And the loop is basic v-for loop
<ul v-for="person in persons">
<li> {{ person.title }}{{ person.name }} - <!-- Inc. external data {{ time.one }} -->
</ul>
The end result being:
Prof. SomeProf - 10:00pm
Dr. SomeDr - 09:00am
Thank You
I don't know if I understood your question properly, but you can also just modify the data right away.
Let's say you have your own data and make a call to the API when the component is created. What you can do is:
import persons from '#/data/persons'
export default {
data() {
return {
dataToLoop: []
}
},
async created() {
const timeData = await yourApiCall();
let results = [];
for (let i in persons) {
results.push({
...persons[i],
time: timeData[i] // or whatever key matches the person
})
}
this.dataToLoop = results;
}
}
And then all you need to do is loop through "dataToLoop" in your component.

how do I access json from gulp data in nunjucks?

I have a some.json file like this:
{
"disneyland-paris": {
"lang": "de"
},
"hanoi": {
"lang": "de"
}
}
… that I want to get into a nunjucks template with:
pipe(data(function() {
return JSON.parse(fs.readFileSync(".../some.json"))
}))
.pipe(nunjucksRender())
How would I access this data within nunjucks?
This does not work:
{{ some }}
or
{{ some.json }}
One of many approaches you could take is use gulp nunjucks render for your gulp project. If you decide to go this route, you can use the following steps as a proof-of-concept to achieve your goal. And if not, you can borrow ideas from the following steps anyway!
Step 1 - Within your project, "you could" structure your JSON data like so in a file called Languages.js :
const languages = [
{
"group": [{
"location":"disenyland-paris",
"lang": "de"
},
{
"location":"hanoi",
"lang": "de"
},
]
}];
module.exports = languages;
Step 2 - From your gulpfile.js, assuming you are running a gulp project, call your JSON data, then reference it within your Nunjucks logic as an environmental global...
...
const nunjucksRender = require('gulp-nunjucks-render');
const Languages = require('./src/models/Languages');
...
const manageEnvironment = function (environment) {
environment.addGlobal('mLangauges',Languages);
}
...
function genNunJucks(cb) {
return src(['src/views/*.html'])
.pipe(nunjucksRender({
path: ['src/views/', 'src/views/parts'], // String or Array
ext: '.html',
inheritExtension: false,
envOptions: {
watch: true,
},
manageEnv: manageEnvironment,
loaders: null
}))
.pipe(dest('pub')); //the final destination of your public pages
cb();
}
//then do more stuff to get genNunJucks() ready for gulp commands...
Step 3 - From within your Nunjucks template file, call the data like so...
{% for sections in mLangauges %}
{% for mgroup in sections.group %}
<p>{{mgroup.location}}</p>
<p>{{mgroup.lang}}</p>
{% endfor %}
{% endfor %}
All that is left to do is run your gulp project :)
Tip - If you change your JSON data while working, you may need to re-build your gulp project to see the udpated JSON data on your web page. Re-building can be as simple as running 'npm run build' if you set it up right in your package.json file.

Show in Html a JSON file in Angular

I'm trying to print a JSON (link to the JSON) in an html file.
JSON:
{
"ricette": {
"FRIGGITRICI": {
"Alici": [
[
{"500": "scongelamento"}
],
[
{"60": "nada"}
]
],
"Baccalà": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
},
"GRIGLIA": {
"Baccalà": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
}
}
}
I've fetched it and saved in a variable:
export class DatiService {
fileJson: JSON;
constructor() { }
private datiUrl = 'https://api.myjson.com/bins/zbfh5';
async getDati(){
await fetch(this.datiUrl)
.then(res => res.json())
.then((out) => {
this.fileJson=out;
});
console.log(this.fileJson);
};
}
How can i print it in the html code?
Can i just use de "." to enter in its fields?
Or it's more complicated?
You can use the JsonPipe in your template.
{{fileJson | json}}
If you want to print a specific part you can navigate via . deeper into the object structure.
{{fileJson.ricette.FRIGGITRICI | json}}
If you want to print a primitiv value interpolation is enough and no json pipe is needed.
{{fileJson.version}}
UPDATE
Did you called your getDati function? Add an ngOnInit Lifecycle Hook and call it there. Here is an working stackblitz sample.
I just realized it's a service in your sample code. Take the service and inject it into a component and call it there.
We can use pre tag to view JSON data in HTML
Pass your JSON in var data.
And Set pre tag in HTML body.
var data = {Your JSON Object}
$("#json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

Angular 5 - async pipe with firebase

I want to add async pipe to angular firebase but i've got error that I don't know how to fix:
ERROR Error: InvalidPipeArgument: '[object Object]' for pipe
'AsyncPipe'
Firebase NoSQL database:
{
"boss" : [ null, {
"isPremium" : true,
"name" : "John",
"students" : 10000
} ],
"users" : [ null, "user", "user2" ]
}
UPDATE
I've changed component code:
user$: AngularFireList<any>;
constructor(db: AngularFireDatabase) {
this.user$ = db.list("/users");
}
html:
<ul>
<li *ngFor="let user of user$ | async">
{{ user }}
</li>
</ul>
I'm getting the same error...
In Angular version 4 it works but, how to fix that in angular 5.2.0 ??
The async pipe works with observables as argument. The error clearly states that user$ field is not an observable.
Maybe you wanted to subscribe to the valueChanges() observable of the db.object()?
Take a look here: https://github.com/angular/angularfire2/blob/master/docs/rtdb/objects.md
UPDATE
It seems that AngularFireList<any> is not an Observable, so you would receive the same error.
As I can see in the documentation of the angularfire2, the list() method returns an object in latest version, which has a valueChanges() method. Consider changing the code by calling the valueChanges() method and using the async pipe onto the resulting observable.
More details here: https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md#50
You're getting that error because, async pipe works with Observables and the data you're returning is not.
You might want to change your code to this:
user$: Observable<any[]>;
constructor(db: AngularFireDatabase) {
this.user$ = db.list("/users").snapshotChanges();
}
Or this:
constructor(db: AngularFireDatabase) {
this.user$ = db.list("/users").valueChanges();
}

using JSON file to define array values in Node.js

In node.js my program app.js, i am defining array like this
var myList = [["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]];
console.log (myList)
It is giving output but i want an external JSON file to supply the parameter of myList array instead of me defining it hardcore
i have prepared a JSON file named ppm.json and change my code to
var myList = JSON.parse(fs.readFileSync('ppm.json', 'utf8'));
console.log (myList[1])
my ppm.json is this
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}
it giving me output as undefined in console. what is the problem. pls help.
Without more requirements it's hard to give a definitive answer, but one thing you can do:
app.js
var myList = require('./my_list.json');
console.log(myList);
my_list.json
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
You can use require() to load both JSON and JavaScript files.
For example,
myFile.json:
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
app.js:
var myList = require( './myFile.json' );
console.log (myList)
You're accessing your item wrong. You don't have an array you have an object.
Access your heros age like this:
myList['age']
You might also consider changing your file to look like this:
{
"SAHRUKH" : {
"age" : "47.49",
"lastpict" : "HIT"
}
}
In which case you'd get your hero's age like:
myList.SAHRUKH.age;
//Or Equivalently
myList['SAHRUKH']['age']; //The dot notation above is preferred though!
Or this
{ "heros" : [
{
"name" : "SAHRUKH",
"age" : "47.49",
"lastpict" : "HIT"
}
]}
In which case you'd get at age like:
myList.heros[0].age;
If you adjust your ppm.json file to look like:
[{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}]
It should drop in and work directly. If you wanted to include multiple heroes, it would look like:
[
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
},
{
"hero": "SALMAN",
"age": "47.3",
"lastpict": "FLOP"
}
]
Your resulting myList should be an array in the example you provided, with entry 0 being the first hero object (SAHRUKH) and 1 being the second, and so on.