Saving dates in Angular 2 and JSON - 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..
Related
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}.
Angular 6 define JSON format of Date
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')) } }
how to add social share button in angular 4
I have run the command "npm install --save ng2-social-share". and then add into app.module.ts :- import { CeiboShare } from 'ng2-social-share'; #NgModule({ imports: [ CeiboShare ] }); and then i add into my home.component.ts :- import { CeiboShare } from 'ng2-social-share'; #Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], directives: [CeiboShare] }) webpack: Compiling... ERROR in src/app/home/home.component.ts(16,3): error TS2345: Argument of type '{ selector: string; templateUrl: string; styleUrls: string[]; directives: typeof CeiboShare[]; }' is not assignable to parameter of type 'Component'. Object literal may only specify known properties, and 'directives' does not exist in type 'Component'. Date: 2018-02-27T09:02:42.288Z - Hash: bedb972b22f9a72ebb59 - Time: 2832ms 5 unchanged chunks chunk {main} main.bundle.js (main) 367 kB [initial] [rendered] webpack: Compiled successfully.
The simple way for you is to import in your app.modules.ts like this 1) import {CeiboShare} from 'ng2-social-share'; #NgModule({ declarations: [ AppComponent, CeiboShare ] }) 2) and then in your home.component.ts you need to just only define the url sharing link and image url sharing if you want like this: //vars used only for example, put anything you want :) public repoUrl = 'https://www.egozola.com'; public imageUrl = 'https://avatars2.githubusercontent.com/u/10674541?v=3&s=200'; the in your home.component.html the you can call sharing easily like this button ceiboShare [facebook]="{u: repoUrl}">Facebook Linkedin Google Plus Twitter Pinterest good all thing is working well
What you could do is to use these functions on your typescript file and call it from the template. Providing here 5 Social Media Share - Facebook, Pinterest, Twitter, GooglePlus, LinkedIn // Facebook share won't work if your shareUrl is localhost:port/abc, it should be genuine deployed url shareOnFacebook(shareUrl: string) { shareUrl = encodeURIComponent(shareUrl); window.open(`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}`, 'sharer'); } shareOnPinterest(shareUrl: string, img: string, desc: string) { shareUrl = encodeURIComponent(shareUrl); img = encodeURIComponent(img); desc = encodeURIComponent(desc); window.open(`https://www.pinterest.com/pin/create/button?url=${shareUrl}&media=${img}&description=${desc}`, 'sharer'); } shareOnTwitter(shareUrl: string, desc: string) { shareUrl = encodeURIComponent(shareUrl); desc = encodeURIComponent(desc); window.open(`https://twitter.com/intent/tweet?url=${shareUrl}&text=${desc}`, 'sharer'); } shareOnGooglePlus(shareUrl: string) { shareUrl = encodeURIComponent(shareUrl); window.open(`https://plus.google.com/share?url=${shareUrl}`, 'sharer'); } // LinkedIn share won't work if your shareUrl is localhost:port/abc, it should be genuine deployed url shareOnLinkedIn(shareUrl: string, title: string, summary: string) { shareUrl = encodeURIComponent(shareUrl); window.open(`https://www.linkedin.com/shareArticle?url=${shareUrl}&title=${title}&summary=${summary}`, 'sharer'); } Hope this will help you or somebody else. Thanks!
remove that directives : [CeiboShare] from #component decorator. It is not supported in angular 4 and you don't even need to import it into your component. Just Import into Ngmodule as below, import { CeiboShare } from 'ng2-social-share'; #NgModule({ imports: [ CeiboShare.forRoot() ] }); This would suffice to get it working in any component as attribute directives.
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;
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] })