How to store a array element in local storage - json

I'm new to ionic 3. i need to store a array element in local storage.
I tried this code but it only storing the array. Not an array element
This is my code:
signin() {
this.showLoader();
console.log(this.loginData);
this.authService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
console.log('Result:'+JSON.stringify(result));
localStorage.setItem('token', JSON.parse(JSON.stringify(this.data))._body.access_token);
console.log(JSON.parse(JSON.stringify(this.data))._body.access_token);
this.navCtrl.setRoot(DashboardPage);
and this is an result value
Result:{"_body":"{\"access_token\":\"J0ErN5qf4btTJaB27FLMNLTrhwBxZMTCBAxc4m25\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\"OMVvOXHgsfKwWtHyYwjlzsO5Jxb44H0Oi9lf7Pk6\"}",
In short, i need to store the access_token in local storage. please suggest some method.
Thanks in advance

The problem is how are you storing the value in the localStorage, the correct implementation would be:
Save to localStorage:
localStorage.setItem('token', JSON.stringify(this.data._body.access_token));
Get from localStorage:
JSON.parse(localStorage.getItem('token'));

Related

React.js: setState method setting variable to a string instead of object... is there a workaround?

I am trying to fetch a simple JSON element from express.js. I am trying have React assign it to a state variable on the front end. I am using this code to do so:
componentDidMount() {
fetch("/user")
.then(response => response.json())
.then(result => this.setState({myUser:result}))
}
But when I run typeof myUser after this setState command, it says string instead of object. I've tried using JSON.parse(), etc. But either I get an error or it continues to assign the data as a string rather than JSON. What sort of syntax do I need to use in this fetch-then context to coerce the data assignment to be JSON?
I have read this link:
With this code:
componentDidMount(){
fetch('https://abx.com/data/tool.json').then(response =>{
if (!response.ok) throw Error('Response not ok')
return response.json(); // This is built in JSON.parse wrapped as a Promise
}).then(json => {
this.setState({"sections" : json});
}).catch(err =>{
console.log(err);
});
}
But it doesn't solve the problem. I ran this code directly in my application verbatim. When I run typeof on the variable, it says string instead of object. I looked at other posts on Stack Overflow, but I did not see a solution to this.
I figured out what was going wrong (after many hours of experimenting):
On the server side, I was creating a "homegrown" JSON object using string and variable concatenation. I also tried creating the JSON object by doing this:
var str = "name:" + name + ", department:" + department
var user = {str};
Both of these were not working in subtle ways... despite trying different types of gadgetry on the client side, I couldn't get React to interpret the data as a JSON object. But then I had an idea to construct the JSON on the server side (in Express.js) like this:
var user = {};
user["name"] = name;
user["department"] = department;
That immediately cleared things up on the server side and the client side. When using setState() in React, it now sets the value as an object (which was the goal all along).
I think this can be useful to others... if React doesn't seem to understand the JSON, perhaps it is being sent from the server in a subtly incorrect format.

How do I output JSON data that has mutiple arrays with in it? Using an Interface?

So I am still kind of a novice at Angular 2. My API call returns an object with several arrays and objects within it.
This is the JSON object I receive when i make the get request
{"report":[{"customer_name":"kaminto" ,
"customer_address":"Second","tel_no":"Second","id":"15","order_no":"RC13",
"total_amount":"28000","amount_paid":"30000","balance":"-2000",
"sale_date":"2017-08-15" ,"customer_id":"21"},"}], "message":"success" ,
"totalSales":[{"amount_paid":"1174300"}]}
I want to output the customer_name and address but they are within the Report array.
Using observables, How can I save this information into objects that i can bind to the html.
Please help.
[SOLVED]
I know this is embarrassing, but i solved it. I just had to add the string type and array brackets to the interface report variable.
export interface ISalesReport{
report:string[];
message:string;
totalSales:string[];
}
I don't know exactly why, but after i did this, it worked.
You get that object from Observable? Yes, it is not necessary if you only need value of two properties. Something like this should help:
customer_name;
customer_address;
yourObservable.map(allReports => allReports.map(report => report
.map(val => { this.customer_name = val.customer_name;
this.customer_address = val.customer_address } ));
Suppose you called your service in your component that returns an observable of the GET call.
In your Service,
getCall() {
return this.http.get(...).map((res) => res.json());
}
In your Component, (say you assign to a property),
responseObj: Observable<any>;
// say you receive values in ngOnInit(),
ngOnInit() {
this.responseObj = this.service.getCall();
}
In your html, use the async pipe for eternally binding it to the observable,
<div [innerHTML]="(responseObj | async)?.report[0].customer_name"></div>
<div [innerHTML]="(responseObj | async)?.report[0].customer_address"></div>
Hope it helps.

Angular2 HTTP Providers, get a string from JSON for Amcharts

This is a slightly messy questions. Although it appears I'm asking question about amCharts, I really just trying to figure how to extract an array from HTTP request and then turn it into a variable and place it in to 3-party javacript.
It all starts here, with this question, which was kindly answered by AmCharts support.
As one can see from the plnker. The chart is working. Data for the chart is hard coded:
`var chartData = [{date: new Date(2015,2,31,0,0,0, 0),value:372.10,volume:2506100},{date: new Date(2015,3,1,0, 0, 0, 0),value:370.26,volume:2458100},{date: new Date(2015,3,2,0, 0, 0, 0),value:372.25,volume:1875300},{date: new Date(2015,3,6,0, 0, 0, 0),value:377.04,volume:3050700}];`
So we know the amCharts part works. Know where the problem is changing hard coded data to a json request so it can be dynamic. I don't think this should be tremendously difficult, but for the life of me I can't seem figure it out.
The first issue is I can't find any documentation on .map, .subscribe, or .observable.
So here is a plunker that looks very similar to the first one, however it has an http providers and injectable. It's broken, because I can't figure out how to pull the data from the service an place it into the AmCharts function. I know how pull data from a http provider and display it in template using NgFor, but I don't need it in the template (view). As you can see, I'm successful in transferring the data from the service, with the getTitle() function.
this.chart_data =_dataService.getEntries();
console.log('Does this work? '+this.chart_data);
this.title = _dataService.getTitle();
console.log('This works '+this.title);
// Transfer the http request to chartData to it can go into Amcharts
// I think this should be string?
var chartData = this.chart_data;
So the ultimate question is why can't I use a service to get data, turn that data into a variable and place it into a chart. I suspect a few clues might be in options.json as the json might not be formatted correctly? Am I declaring the correct variables? Finally, it might have something to do with observable / map?
You have a few things here. First this is a class, keep it that way. By that I mean to move the functions you have inside your constructor out of it and make them methods of your class.
Second, you have this piece of code
this.chart_data =_dataService.getEntries().subscribe((data) => {
this.chart_data = data;
});
What happens inside subscribe runs asynchronously therefore this.chart_data won't exist out of it. What you're doing here is assigning the object itself, in this case what subscribe returns, not the http response. So you can simply put your library initialization inside of the subscribe and that'll work.
_dataService.getEntries().subscribe((data) => {
if (AmCharts.isReady) {
this.createStockChart(data);
} else {
AmCharts.ready(() => this.createStockChart(data));
}
});
Now, finally you have an interesting thing. In your JSON you have your date properties contain a string with new Date inside, that's nothing but a string and your library requires (for what I tested) a Date object, so you need to parse it. The problem here is that you can't parse nor stringify by default a Date object. We need to convert that string to a Date object.
Look at this snippet code, I used eval (PLEASE DON'T DO IT YOURSELF, IS JUST FOR SHOWING PURPOSES!)
let chartData = [];
for(let i = 0; i < data[0].chart_data.length; i++) {
chartData.push({
// FOR SHOWING PURPOSES ONLY, DON'T TRY IT AT HOME
// This will parse the string to an actual Date object
date : eval(data[0].chart_data[i].date);
value : data[0].chart_data[i].value;
volume : data[0].chart_data[i].volume;
});
}
Here what I'm doing is reconstructing the array so the values are as required.
For the latter case you'll have to construct your json using (new Date('YOUR DATE')).toJSON() and you can parse it to a Date object using new Date(yourJSON) (referece Date.prototype.toJSON() - MDN). This is something you should resolve in your server side. Assuming you already solved that, your code should look as follows
// The date property in your json file should be stringified using new Date(...).toJSON()
date : new Date(data[0].chart_data[i].date);
Here's a plnkr with the evil eval. Remember, you have to send the date as a JSON from the server to your client and in your client you have to parse it to a Date.
I hope this helps you a little bit.
If the getEntries method of DataService returns an observable, you need to subscribe on it to get data:
_dataService.getEntries().subscribe(
(data) => {
this.chart_data = data;
});
Don't forget that data are received asynchronously from an HTTP call. The http.get method returns an observable (something "similar" to promise) will receive the data in the future. But when the getEntries method returns the data aren't there yet...
The getTitle is a synchronous method so you can call it the way you did.

Reaching a specific property of the data json object

I would like to reach a specific property of the data that I have returned from my service.
So basically I want to be able to somehow reach $scope.users.name, I know that the users are the objects in the array, but could I reach that specific property in any way? Hopefully the question is clear enough?
$scope.users = [];
UserService.getAll().then(
function (data) {
$scope.users = data;
}, function (err) {
console.log(err);
}
);
I am assuming the data you receive is in the form of an array. If you know the index then you can do
$scope.users[2].name
Where 2 is the index of the object you want to know the name property of.
Or you can try a js function forEach
$scope.users.forEach(function (user) {
console.log(user.name);
});
The function will iterate over all the objects and you can access their properties inside the callback which is passed in.
Hope that is what you're looking for.

WinJS: Save observable objects without backingData etc. to JSON

what is the best way to save observable objects to JSON without _backingData etc.?
For example instead of:
[{"_backingData":{"name":"Test","hourlyRate":""},"name":"Test","hourlyRate":"","id":-1,"number":"","backingData":{"name":"Test","hourlyRate":""}}]
This should be saved:
[{"name":"Test","hourlyRate":"","id":-1,"number":""}]
This is my code to save the data:
var data = JSON.stringify(value.concat());
Windows.Storage.ApplicationData.current.localFolder.createFileAsync("customer.json", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, data);
});
value is a WinJS.Binding.List().
Is there a simple solution to solve this "problem"?
use WinJS.Binding.unwrap over the individual elements in the array.