Angular 2 Form Serialization Into JSON Format - json

I am having a little bit of trouble creating my Angular 2 form and converting the submitted data into JSON format for the use of submitting it to my API. I am looking for something that works very similarly to this example:
$.fn.serializeObject = function()
http://jsfiddle.net/sxGtM/3/The only problem with this example is that the code is written in JQuery, whereas I'm trying to use strictly angular 2.
Any help would be greatly appreciated, I am still very new to angular.

You can use the getRawValue() function if you're using a FormGroup, to return an object that can then be serialized using JSON.stringify().
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder } from '#angular/forms';
import { Http } from '#angular/http';
#Component({
selector: 'my-component',
templateUrl: 'my-component.component.html'
})
export class MyComponent implements OnInit {
form: FormGroup;
constructor(private fbuilder: FormBuilder,
private http: Http) { }
ngOnInit(){
this.form = this.fbuilder.group({
name: '',
description: ''
});
}
sendToAPI(){
let formObj = this.form.getRawValue(); // {name: '', description: ''}
let serializedForm = JSON.stringify(formObj);
this.http.post("www.domain.com/api", serializedForm)
.subscribe(
data => console.log("success!", data),
error => console.error("couldn't post because", error)
);
}
}

You can use JSON.stringify(form.value):
submit() {
let resource = JSON.stringify(this.form.value);
console.log('Add Button clicked: ' + resource);
this.service.create(resource)
.subscribe(response => console.log(response));
}
Result in Chrome DevTools:

You are looking for JSON.stringify(object) which will give you the JSON represantation of your javascript object.
You can then POST this using the built-in HTTP service to your server.

Related

How to extract data from SafeSubscriber?

I have to make an Angular application in which i get data from the back-end and display it on the front-end, but with some added hard-coded data.
My communication is between 2 files:
client.service.ts
import { Injectable } from '#angular/core';
import {HttpClient, HttpHeaders} from "#angular/common/http";
import {environment} from "../environments/environment";
import {catchError, map, Observable, of} from "rxjs";
const clientUrl = environment.apiUrl+'client';
#Injectable({providedIn: 'root'})
export class ClientService {
public optional: any;
constructor(private http: HttpClient) {}
getText(): Observable<any> {
console.log("it works!");
return this.http.get(clientUrl+"/getText").pipe(map(res => {
console.log(res);
this.optional = res.toString();
}));
}
}
and the second one:
client.component.ts
import { Component, OnInit } from '#angular/core';
import {ClientService} from "../client.service";
#Component({
selector: 'app-client',
templateUrl: './client.component.html',
styleUrls: ['./client.component.css']
})
export class ClientComponent implements OnInit {
public textResponse: any;
constructor(public service: ClientService) {}
ngOnInit(): void {}
getText() {
let text: any;
this.textResponse = this.service.getText().subscribe();
console.log(this.textResponse);
text = this.textResponse + "This text is added from code.";
console.log(text);
}
}
When i call "this.http.get(clientUrl+"/getText")" I get a SafeSubscriber object, from which i managed to get the data displayed in the console using the method ".subscribe(...)" with a "console.log()" inside of it. However, i did not find any method to extract the data out of this subscribe.
As the code above shows, i have tried to use pipe and map, but the local variable is returned as [Object object], and when i print it in the console i get either undefined, either nothing.
This is what my code currently displays:
it works! [client.service.ts:33]
SafeSubscriber {initialTeardown: undefined, closed: false, _parentage: null, _finalizers: Array(1), isStopped: false, …} [client.component.ts]
[object Object]This text is added from code. [client.component.ts]
{text: 'This text is read from a file.'} [client.service.ts]
I have also tried all the suggestions found in questions below:
angular 2 how to return data from subscribe
Angular observable retrieve data using subscribe
Does anyone know a method in which i could get the data out of the Subscribe?
You are missing the return keyword when mapping the response, looking at the console.log, you need the text property
getText(): Observable<any> {
console.log("it works!");
return this.http.get(clientUrl+"/getText").pipe(map(res => {
console.log(res);
this.optional = res.toString();
return res.text;
}));
}

Parsing json response from Http Request in Angular

I need to parse a json response containing two keys.
The response looks like
{
status: 0;
message: 'some error 404'
}
In pure nodejs or React you could just simply do: if (response.status===1)console.log('success').
However, I've been having a tough time doing this in angular. Could someone guide me and tell me how could I parse the JSON Response?
I have attached a mock-up of the code.
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Component } from '#angular/core';
#Component({
selector: 'app-create-employee',
templateUrl: './create-employee.component.html',
styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent {
constructor(private http: HttpClient) { };
onFormSubmit() {
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
let body = new URLSearchParams();
body.set('data', 'stackoverflow');
this.http.post('http://localhost:8080/createEmployee', body.toString(), options)
.subscribe(response => {
console.log(response.status);
console.log(response.message);
});
}
}
According to the documentation, Angular can parse for you objects from string responses if you tell it how to do it. You can use this as an example.
First define an interface inside your component just below your imports:
export interface Response {
status: number,
message: string
}
This tells angular how to parse the json response from your server. The final bit is to use this interface in your post request like this:
this.http.post<Response>('http://localhost:8080/createEmployee', body.toString(), options)
.subscribe(response => {
console.log(response.status);
console.log(response.message);
});

Angular2 include html from server into a div

I got a serie of html in my server. For example:
http://docs.example.com/intro.html
http://docs.example.com/page1.html
http://docs.example.com/page2.html
And I trying to include those files into a<div> in my angular2 v4 app. For example:
component.ts
public changePage(name: string) {
switch (name) {
case 'intro': this.myHtmlTemplate = 'http://docs.example.com/intro.html'; break;
case 'page1': this.myHtmlTemplate = 'http://docs.example.com/page1.html'; break;
case 'page2': this.myHtmlTemplate = 'http://docs.example.com/page2.html'; break;
}
}
component.html
<div [innerHtml]="myHtmlTemplate"></div>
but it doesnt work. I tried the following solutions:
Angular4 Load external html page in a div
Dynamically load HTML template in angular2
but it doesn't work for me. Can somebody help me with this problem please ?
Angular security Blocks dynamic rendering of HTML and other scripts. You need to bypass them using DOM Sanitizer.
Read more here : Angular Security
DO below changes in your code :
// in your component.ts file
//import this
import { DomSanitizer } from '#angular/platform-browser';
// in constructor create object
constructor(
...
private sanitizer: DomSanitizer
...
){
}
someMethod(){
const headers = new HttpHeaders({
'Content-Type': 'text/plain',
});
const request = this.http.get<string>('https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form', {
headers: headers,
responseType: 'text'
}).subscribe(res => this.htmlString = res);
this.htmlData = this.sanitizer.bypassSecurityTrustHtml(this.htmlString); // this line bypasses angular security
}
and in HTML file ;
<!-- In Your html file-->
<div [innerHtml]="htmlData">
</div>
Here is the working example of your requirement :
Working Stackblitz Demo
This should do it:
First in your component.ts get the html with a http request:
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators'
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) { }
htmlString: string;
ngOnInit() {
const headers = new HttpHeaders({
'Content-Type': 'text/plain',
});
const request = this.http.get<string>('https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form', {
headers: headers,
responseType: 'text'
}).subscribe(res => this.htmlString = res);
}
}
And in your component.html simply use a one way data binding:
<div [innerHTML]="htmlString"></div>
You actually want to display a page inside your angular app right?
For that you can add a iframe tag:
<iframe width="400" height="600" [src]="myHtmlTemplate"></iframe>
you have to get HTTP call to load HTML in plain text and load in div using innerHtml.
export class AppComponent implements OnInit {
name = 'Kissht';
KisshtHtml;
constructor(
private http:HttpClient,
private sanitizer:DomSanitizer){ }
ngOnInit(){
this.http.get('https://kissht.com/',
{responseType:'text'}).subscribe(res=>{
this.KisshtHtml = this.sanitizer.bypassSecurityTrustHtml(res);
})
}
}
Sometime you might get CORS issue in stackblitz whil loading external Html
https://stackblitz.com/edit/display-external-html-into-angular
In your component first request pages with HTTP request
this.http.get('http://docs.example.com/intro.html').map(response => response.text()).subscribe(html => Your_template = html);
use innerhtml with the safehtml pipe so your inline styling will be applied
more info on GitHub page(https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1)
<div [innerHtml]="Your_template | safeHtml"></div>

Importing JSON from a server within Angular

I am reading data from a JSON, which is one a server and it updates regularly and changes. I need to be able to read this JSON from the server so that I display the most up to date information on my web page.
Currently, the to be able to read the JSONs they are stored within the same project folder as my angular project. (This was because they were not set up on the server when I started).
This is how I currently import the JSON to be able to read it:
import jsonInfo from '../../../info.json'
I thought I would be able to change the file link to the server address, like so:
import jsonInfo from 'http://servername/folder/info.json'
But, VSCode gives me an error: Cannot find module 'http://servername/folder/info.json'
This is definitely the location of the JSON I am trying to load because when I click the link it takes me to the JSON and displays it.
My question is, how do I import the JSON into my .ts from a server so that I can keep getting the updated information from the JSON?
JSON file on a server is just like any other web resource you would try to access (like an API endpoint, for example).
So you should use built in angular http client to access this JSON file.
For example:
import { HttpClient } from '#angular/common/http';
export class SomeService {
constructor(private http: HttpClient) { }
getInfo() {
return this.http.get('http://servername/folder/info.json');
}
}
//...
export class SomeComponent implements OnInit {
info: any;
constructor(private someService: SomeService) {}
ngOnInit() {
this.someService.getInfo().subscribe(info => this.info = info)
}
}
Use HttpClient get method.
this.httpClient.get('http://servername/folder/info.json').subscribe(data => {
// your logic
})
You can use HttpClient and do like as shown below
Working Demo
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
data = [];
apiUrl = 'http://servername/folder/info.json';
GetData() {
this.http.get<any[]>(this.apiUrl)
.subscribe(data => {
this.data = data;
});
}
ClearData() {
this.data = [];
}
constructor(private http: HttpClient) {}
ngOnInit() {}
}

Console output shows "undefined" when attempting to retrieve and map JSON data in Angular 6

I'm trying to learn how to get JSON data from an api, parse and map it to my type and then display it in an angular material datatable. However when I check my console output, it shows the value as undefined. I haven't even got as far as creating the datatable.
Can anyone tell me where I am going wrong? I'm using Angular 6.1.0:
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from '../../node_modules/rxjs';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'NgTable';
myPlace = "https://jsonplaceholder.typicode.com/posts";
myPosts: Observable<posts[]>;
myPostArr: posts[];
constructor(http: HttpClient){
this.myPosts = http.get<posts[]>(this.myPlace);
this.myPosts.subscribe(response => {this.myPostArr = response});
console.log(this.myPostArr);
}
}
export interface posts {
userId: number;
id: number;
title: string;
body: string;
}
output of console.log is: undefined
Due to async nature of observable, this.myPostArr gets data at some point of time
So, out side of subscribe block, it won't be resolved when that line executes.
I will suggest you to put all your http methods in a service and return Observables.
constructor(http: HttpClient){
this.myPosts = http.get<posts[]>(this.myPlace);
this.myPosts.subscribe(response => {this.myPostArr = response;
console.log(this.myPostArr);
});
}