Angular 6 define JSON format of Date - json

I want to make a POST request to an API. The API expects a date in the following format yyyy-MM-dd HH:mm:ss.SSS.
I have a request object with an attribute of Type Date.
When I make the POST request via
this.http.post<ResponseObject>(url, objectWithDateAttribute, headers);
My API throws an error because the JSON format of the attribute of type date doesn't match.
How can I change the JSON format of the Date attribute when I make the POST request?

The API requires an ISO String you can obtain by calling toISOString() method on your date object.

Your format is yyyy-MM-dd HH:mm:ss.SSS.
let dateAttrib = new Date().toISOString().split('T').join(' ');

You can do it using angular DatePipe. You can convert the date object objectWithDateAttribute by looking at this sample example. Note the providers array and it should also be injected inside the constructor.
import { Component } from '#angular/core';
import { DatePipe } from '#angular/common';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers : [DatePipe]
})
export class AppComponent {
someDate = new Date();
constructor(private dp : DatePipe) {
console.log(this.dp.transform(this.someDate, 'yyyy-MM-dd HH:mm:ss.SSS'))
}
}

Related

how to parse a List of Objects in a json file and display it?

I'm trying to use the import method to parse a json file, this is what my code looks like.
import { Component } from '#angular/core';
import * as data from './cities.json';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'weather-app';
cities: any = (data as any).default;
constructor(){}
ngOnInit(){
console.log(data);
}
}
and this is how i'm trying to display it,
<ul *ngFor="let c of cities">
<li>{{c.CityName}}</li>
</ul>
My console log displays everything but it does not appear in the angular app list, What am i doing wrong here? I'll post the json file i'm trying to parse below. thanks in advance :)
{"List":
[{"CityCode":"1248991","CityName":"Colombo","Temp":"33.0","Status":"Clouds"},
{"CityCode":"1850147","CityName":"Tokyo","Temp":"8.6","Status":"Clear"},
{"CityCode":"2644210","CityName":"Liverpool","Temp":"16.5","Status":"Rain"},
{"CityCode":"2988507","CityName":"Paris","Temp":"22.4","Status":"Clear"},
{"CityCode":"2147714","CityName":"Sydney","Temp":"27.3","Status":"Rain"},
{"CityCode":"4930956","CityName":"Boston","Temp":"4.2","Status":"Mist"},
{"CityCode":"1796236","CityName":"Shanghai","Temp":"10.1","Status":"Clouds"},
{"CityCode":"3143244","CityName":"Oslo","Temp":"-3.9","Status":"Clear"}]}
This is because your root object is not of type Array, your object is
{
List: city[]
}
You may access the property List
<ul *ngFor="let c of cities.List">
<li>{{c.CityName}}</li>
</ul>
Note: that your code needs refactoring as it does not appear as clean code. my answer is just to show to you where is the mistake

Angular 6 return JSON result intead of HTML template

Is it possible to return JSON result from Angular instead of the HTML template coz we want to build something similar to a API-server? Thanks.
Here is the example that return the HTML template, how can we just return JSON without using template?
What I want to return is just a simple json result instead of HTML.
{"ID" : "1", "Name" : "Apple"}
Here is the code.
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-noresultsfound',
templateUrl: './noresultsfound.component.html',
styleUrls: ['./noresultsfound.component.css']
})
export class NoresultsfoundComponent implements OnInit {
#Input() txtval: string;
constructor(private app: AppConstants) { }
noresultsfound = this.app.noresultsfound;
ngOnInit() {
}
}
Alex
I think, he meant that pure JSON should be returned to who ever requested it by endpoint request. At least i faced something like this.
For static json, i've found an answer: https://github.com/angular/angular-cli/issues/5029
bresleveloper commented on 6 Jul 2018
1. ng-build with your index.html set properly with its components. (or conditional app-components)
2. rename and copy the rendered to (for example) /src/search.html
3. in angular.json (angular-cli.json for pre v5) find "assets":
"assets": [
"src/favicon.ico",
"src/search.html",
"src/assets"
],
browse localhost:4200/search.html
enjoy :)
Interesting part comes when u try to generate that json somehow, with browser not being involved - like some automatic service sends a request to some angular endpoint, like: hosname/statistics and in response, it receives a json which depends on number of pictures and headers on this current hosname, like {siteName: 'test', pictures: 10, headers: 1}.

Splitting json data in angular2

I am using angular2 to fetch data from node api. Node api returns data in a format like that
{"height":{"low":4,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":38,"markedOffset":-1,"limit":70,"littleEndian":true,"noAssert":false}}
I only want to display value of low in angular2 frontend but problem is I am unable to split that json data into key-value pairs. Either angular2 is displaying whole data or nothing.
This is my component code which receives data in json format
import {Component,OnInit} from '#angular/core';
import { AppService } from '~/./../app/app.service';
#Component({
selector: 'dashboard',
styleUrls: ['./dashboard.scss'],
templateUrl: './dashboard.html'
})
export class Dashboard implements OnInit {
constructor(private AppService: AppService) {
}
ngOnInit(){
this.getStats();
}
BlockchainHeight:any;
getStats(){
this.AppService.getblockchaininfo().subscribe(data=>{
console.log(data);
this.BlockchainHeight=data["_body"];
});
}
}
And this is my html code which display data
<div class="row">
<div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4">
<ba-card>
<h3> Blockchain Height</h3>
{{BlockchainHeight}}
</ba-card>
</div>
Any trick or solution to split that json data into key value pairs?
Im not sure about the specifics regarding Angular2, but this will convert a json string into an object with just plain vanilla javascript
var jsonResponse = "{"height":{"low":4,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":38,"markedOffset":-1,"limit":70,"littleEndian":true,"noAssert":false}} ";
var decodedJsonObject = JSON.parse(jsonResponse);
var low = decodedJsonObject.height.low;

Saving dates in Angular 2 and JSON

This has been a very difficult problem I have run into with my Angular 2 app. I am trying to format my API (MongoDB) so that each new "post" added by the admin can be fetched by the DATE (not time) by the front end. For example, my schema looks like this:
{name: "The best product ever",date: "25092016",quantity: 345},{name:"The okayest product ever",date: "26092016",quantity: 544,}
As you can tell, the date property is a single number. I then have a function that fetches the data from the object with the current date. However, this is the problem. The date format I am using for the JSON is 'ddMMyyyy'. This worked well for the date pipe in the HTML template, but I cannot seem to be able to format any date in a variable to match this format, or a similar format. All the dates in Angular 2 classes show GMT and timestamps, etc.
How to I format a date in Angular 2 components to match a short succinct string format?
You can use that DatePipe even in your code. :)
https://plnkr.co/edit/6pbHMVSTmndvs9CqYYUL?p=preview
import {Component, NgModule} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import {DatePipe} from '#angular/common';
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
let dp = new DatePipe('de-DE' /* locale .. */);
this.name = dp.transform(new Date(), 'ddMMyyyy');
console.log(name);
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Or you want to use a library like Moment.js..

How to format MySQL datetime to angular2 useable date format in Ionic 2?

I am trying to format a mysql datetime that looks like this: 2016-05-27 20:17:45 to an useable date format for angular2. After reading some comments how this could be done I created a custom pipe:
import {Pipe} from 'angular2/core';
#Pipe({
name: 'dateToIso'
})
export class DateToIso {
transform(value, args) {
let newValue = new Date(value).toISOString();
return newValue;
}
}
Then I imported the pipe to the page where to use it and defined it in the decorator to use it in the HTML file.
import {DateToIso} from '../../pipes/date-ToIso';
...
#Page({
templateUrl: 'build/pages/page1/page1.html'
pipes: [DateToIso]
})
When using the new created pipe in the HTML file: {{ post[2] | dateToIso}} I get the error:
Error: Uncaught (in promise): Template parse errors: The pipe
'dateToIso' could not be found
What am I doing wrong? Thanks to all :)
There is a missing comma after the template url
#Page({
templateUrl: 'build/pages/page1/page1.html', // << this comma here
pipes: [DateToIso]
})