Cannot display JSON API result from console to html page - javascript

Cannot display the console result in the html page
and this is the code of the TS component (home.component.ts)
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
import {Router } from '#angular/router';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(
private http: Http,
public router:Router
) {}
ngOnInit() {}
source="";
destination="";
date="";
names="";
searchCity(){
this.http.get("http://127.0.0.1:8000/restapi/?source="+this.source+"&destination="+this.destination+"&date="+this.date+"")
.subscribe(
(res:Response) => {
this.router.navigate(['test']);
const searchFlight= res.json();
console.log(searchFlight);
//this.names = searchFlight.names;
}
)
}
}
This is the page where i want to display the result (test page) (this.router.navigate(['test']);)
(test.component.html)
<div class="hl1"></div>
{{names}}
{{prices}}
<div class="hl1"></div>
and thess are the params i get
(home.component.html)
<input type="text" placeholder="From ..." [(ngModel)]=source name="source">
<input type="text" placeholder="To ..." [(ngModel)]=destination name="destination">
<input type="text" class="input datepicker" value="Mm/Dd/Yy" [(ngModel)]=date name="date">
<button (click)=searchCity() type="submit">Search</button>
and this is the console result
enter image description here

Conosole.log is to show debug prints in Console no in HTML.
To see the service results in HTML you must to get them from response object
example:
... first init you variables to see them on html
this.names = "Sample"
this.prices = 5;
... then apply this code inside your function
this.http.get("http://127.0.0.1:8000/restapi/?source="+this.source+"&destination="+this.destination+"&date="+this.date+"")
.subscribe(
(res:Response) => {
this.router.navigate(['test']);
searchFlight= res.json();
console.log(searchFlight);
this.names = searchFlight.names;
this.prices = searchFlight.prices;
}
)
... Advice: check you api result, and check if you problem is just update the DOM

The way you are trying to see the data will only show you on the Console. You can use Firebug or Chrome Developer Tools (Ctrl+Shift+I) and you can see the object. If you need to print it on the screen you can do something like this:
...
export class HomeComponent implements OnInit {
constructor( private http: Http, public router:Router ) {}
ngOnInit(){}
get printObject() {return JSON.stringify(this.object)}; //set this method
and you can use this in your template like
<div> {{printObject}} </div>
What this does is sets a method on the controller that returns a stringified representation of the object. If you have an array, try something like this in your template
<ul>
<li *ngFor="let object of array">{{object | json}}</li>
</ul>

Related

Angular array works in console but not in dom

thank You for reading. I'm a Angular beginner and have an first problem I can't solve. I read many, many posts without success, sorry.
My seach form is working fine if I get the search phrase in one component and process it in another component. The *ngFor loop gives back the right result-array in dom and console: searchCustomer(phrase).
The exactly same search function works not, if I include a header component with another search form - although I get the right results via console(!). I included the header via app-header in component.html.
Why contains the array "results" the right items but the dom isn't showing it? This is my code:
search.component.html:
<form #f = "ngForm" action="verification" method="get">
<input [(ngModel)] = "phrase" type="text" name="phrase">
<button type="button" (click)="searchCustomer()">Search</button>
</form>
search.component.ts:
searchCustomer() {
this.dataService.setPhrase(this.phrase); // store phrase
this.router.navigate(['/results']); // navigate
}
result.component.html:
<app-header></app-header>
<div class="col-md-6" *ngFor="let vs of results">
...
</div>
result.component.ts:
import { ChangeDetectorRef, Component, OnInit } from '#angular/core';
// add ApiService
import { ApiService } from '../~services/api.service'; // ApiService
// add customers Model
import { Customer } from '../~interfaces/customers';
// DataService
import { DataService } from "../~services/data.service";
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css'],
})
export class ResultComponent implements OnInit {
// add array:
results: Customer[];
// add variable
phrase: string;
constructor(
private apiService: ApiService,
private dataService: DataService,
private cdr: ChangeDetectorRef
) {
}
ngOnInit() {
}
searchCustomer(phrase) {
// search
this.apiService.searchCustomer(phrase).subscribe((result:Customer[]) => {
this.results = result;
console.log(this.results);
this.cdr.detectChanges();
}
)
}
}
header.component.html:
<form #f = "ngForm">
<input type="text" [(ngModel)] = "phrase" type="text" value="{{phrase}}">
<button type="button" (click)="searchCustomer()">Search</button>
</form>
header.component.html:
searchCustomer(){
this.dataService.setPhrase(this.phrase);
this.resultComponent.searchCustomer(this.phrase);
}
If I start the search from Header, I can see the correct array "results" in Console, but not in dom. There is no refreshing.
Thank you for eye-opening,
Matthias
This was the solution in result.component.ts
responsePage$: Observable<ResponsePage>;
ngOnInit() {
this.apiService.searchCustomer(phrase).subscribe((result:Customer[]) => {
this.results = result;
this.searchCustomer(phrase);
});}
searchCustomer(phrase) {
this.responsePage$=this.apiService.customers(phrase);
}

Angular: How to get value from one component's frontend (app.compont.html) to another component's backend (other.component.ts)

Consider a simple crud scenario. I have a lot of input fields and buttons in app.component.html. When i press a button from app.component.html, it will send html field value to 'other.component.ts' component and will display the result back in app.component.html after processing (like add, subtract or other).
Here is app.component.html
<a routerLink="posts/">Show Posts</a>
<input type="number" [(ngModel)]="get-one-post-id">
<a routerLink="/post-by-id">Show One Posts</a>
<router-outlet>
</router-outlet>
post-by-id-component.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-post-by-id',
templateUrl: './post-by-id.component.html',
styleUrls: ['./post-by-id.component.css']
})
export class PostByIdComponent implements OnInit {
posts: object;
constructor(private dataService: DataService) { }
ngOnInit(): void {
// const id = ??
this.GetPost(1);
}
async GetPost(id: number)
{
const response = await this.dataService.Get_A_Post(id);
const dataService = await response.json();
this.posts = dataService;
}
}
post-by-id-component.html
<div *ngFor="let post of posts">
<h3>{{post.title}}</h3>
<p>{{post.body}}</p>
</div>
I just want to get value from the field called get-one-post-id from app.component.html to post-by-id-component.ts [where I commented // const id = ??]. But i can't find a way to import it.
To share Data between Angular Components exists 4 different ways:
Parent to Child: Sharing Data via Input
Child to Parent: Sharing Data via ViewChild
Child to Parent: Sharing Data via Output() and EventEmitter
Unrelated Components: Sharing Data with a Service
You can read this useful article to see how it works.

Unable to get the text field value in typescript using angular

I have two type of Request that I need to fetch from the Angular UI page and pass it into app.component.ts file so that I can call my REST client through HTML page.
Request 1:
End Point: (GET call)
http://localhost:8081/api/products?productId=7e1308ba2b9af
I just created a text field in the app.component.html file as like below:
<div>
<input type="text" placeholder="Product ID" class="user_id_text"/>
</div>
<div>
<input type="submit" value="submit"/>
</div>
Output:
I have written the below code and ensured it works as expected by using the hard-coded value.
app.component.ts:
ngOnInit():void{
this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{
console.log(data);
});
}
The above code return data array with proper response. But the above productId value is hard-coded (7e1308ba2b9af). And I just want to get that value from HTML text box when user click the submit button and pass it to query param and run the above request.
Request 2:
I have to get the below format json file from text box and pass it as JSON request body to the below end point URL.
End Point: (PUT call)
https://localhost:8081/api/updateRecord
Request JSON:
{
"productId":234242882,
"purchaseDate" : "2019-12-20",
"status": "dispatched"
}
I just want to create a text field and get the above json file if user click submit button and invoke the above end point.
I'm very new to the Angular and not sure how to implement this. I just googled but I didn't understand the way they resolved. It would be much appreciated if someone explain me the things and guide me to resolve this.
for request 1:
put a id to your input tag and then try this:
let variableValue = (<HTMLInputElement>document.getElementById("idproduct")).value
or
let variableValue = document.getElementById("idproduct").innerHTML
Request 1
We can use ReactiveFormsModule to allow us to get the value from user input directly and then feed it dynamically to the api.
We also need to import HttpClientModule
To achieve this:
app.module.ts
import {ReactiveFormsModule} from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [...],
imports: [...,ReactiveFormsModule, HttpClientModule],
providers: []...
After you have imported ReactiveFormsModule,and HttpClientModule we can now use FormBuilder and FormGroup to allow us to dynamically keep track of user input and HttpClient to send get requests to our api.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
productIDForm: FormGroup;
httpHeaders: new HttpHeaders({
'Content-Type': 'application/json',
})
constructor(
private formBuilder: FormBuilder,
private http: HttpClient
) { }
ngOnInit() {
this.productIDForm = this.formBuilder.group({
'productID': [null, [Validators.required, Validators.nullValidator]]
})
}
onSubmit() {
if (this.productIDForm.invalid) return;
this.getProduct(this.productID.get('productID').value).subscribe(
(res) => {
console.log(res);
// If the request was successful then `res` contains the information about the product.
},
(err) => {
console.log(err);
// If the request failed, `err` contains the information why the failure occured
)
}
getProduct(productID: string): Observable<any> {
return this.http.get(
`http://localhost:8081/api/products?productId=${productID}`,
{ headers: this.httpHeaders }
)
}
}
We now need to bind the input field to productIDForm.
app.component.html
<form [formGroup]="productIDForm">
<input formControlName="productID" type="text" class="user_id_text"/>
</form>
<div>
<input (click)="onSubmit()" type="button" />
</div>
Request 2
We still use the ReactiveFormsModule, FormBuilder and FormGroup to dynamically fetch the user input and sort of bind it to the api PUT request.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
productIDForm: FormGroup;
httpHeaders: new HttpHeaders({
'Content-Type': 'application/json',
})
constructor(
private formBuilder: FormBuilder,
private http: HttpClient
) { }
ngOnInit() {
this.productDetailsForm = this.formBuilder.group({
'productID': [null, [Validators.required, Validators.nullValidator]],
'purchaseDate': [null, [Validators.required, Validators.nullValidator]],
'status': [null, [Validators.required, Validators.nullValidator]]
})
}
onSubmit() {
if (this.productDetailsForm.invalid) return;
let recordNewDetails = {
"productId": this.productDetailsForm.get('productID').value,
"purchaseDate": this.productDetailsForm.get('purchaseDate').value,
"status": this.productDetailsForm.get('status').value
}
recordNewDetails = JSON.stringify(recordNewDetails); // This will format `recordNewDetails` to JSON format.
this.updateRecord(recordNewDetails).subscribe(
(res) => {
console.log(res);
// If the request was successful then `res` contains the information about the product.
},
(err) => {
console.log(err);
// If the request failed, `err` contains the information why the failure occured
)
}
updateRecord(productDetails: {}): Observable<any> {
return this.http.put(
`https://localhost:8081/api/updateRecord`m
productDetails,
{ headers: this.httpHeaders }
)
}
}
app.component.html
<form [formGroup]="productDetailsForm">
<input formControlName="productID" type="text" class="user_id_text"/>
<input formControlName="purchaseDate" type="date">
<select formControlName="status">
<option disabled>Select Status Option</option>
<option>Dispatched</option>
</select>
</form>
<div>
<input (click)="onSubmit()" type="button" />
</div>
Use [(ngModel)] to bind an input to a variable:
<div>
<input type="text" [(ngModel)]="productId" placeholder="Product ID"
class="user_id_text"/>
</div>
Use (click) to bind a button to a function:
<div>
<input type="submit" (click)="getById(productId)" value="submit"/>
</div>
In the controller:
ngOnInit():void {
this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{
console.log(data);
});
}
getById():void {
const base:string = "http://localhost:8081/api/products";
const url:string = `${base}?productId=${this.productId}`;
this.http.get(url).subscribe(data =>{
console.log(data);
});
}

HTTP GET Request in Angular 7 returning Error (status 200)

I believe that I am getting an object back from the wikimedia API, however can't figure out how I can parse it to display.
//app.component.ts
import { Component } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Post } from './post';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Wiki Search';
// readonly ROOT_URL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=japan&origin=*&format=json';
readonly ROOT_URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry Potter&origin=*&callback=JSON_CALLBACK';
// https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=japan"
posts: Observable<any>;
constructor(private http: HttpClient) {}
getPosts(){
this.posts = this.http.get(this.ROOT_URL)
}
}
//app.component.html
<input type="text" placeholder="Search for pages..">
<button (click)="getPosts()">Get Posts</button>
<div *ngFor="let post of posts | async">
{{ post | json }}
</div>
<ul class=filter-select>
<li class="filter-select-list">
<p class="wiki-page"></p>
</li>
</ul>
If I insert responseType: text into the response handler, I am able to read the returned data as an error in dev console.
the URL you are calling ends with a queryString parameter callback=JSON_CALLBACK
https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry%20Potter&origin=*&callback=JSON_CALLBACK
This is wrapping the JSON in a callback method called JSON_CALLBACK, which is not a valid JSON and wouldn't allow parsing. I tried without that queryString parameter and the response is now a valid, pure JSON, which you should be able to parse
https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry%20Potter&origin=*

Angular form returning ERROR TypeError: "_co.service.formData is undefined"?

I'm trying to make an form in angular 7 and get inout in that but the form is giving the following error : ERROR TypeError: "_co.service.formData is undefined"
now here is my code for the html part of the component :-
<form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm">
<div class="form-group">
<input name="Name" class="form-control" #Name="ngModel" [(ngModel)]="service.formData.Name" required>
</div>
</form>
while this is the type script code
import { Component, OnInit } from '#angular/core';
import {UserService} from '../../shared/user.service';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-agent-signup',
templateUrl: './agent-signup.component.html',
styleUrls: ['./agent-signup.component.css']
})
export class AgentSignupComponent implements OnInit {
constructor(private service:UserService) { }
ngOnInit() {
}
signUp(form:NgForm)
{
}
}
and this is the code for user.service :-
import { Injectable } from '#angular/core';
import {UserData} from './user.model';
import {HttpClient} from '#angular/common/http';
import {environment} from '../../environments/environment';
const API_URL=environment.apiUrl;
#Injectable({
providedIn: 'root'
})
export class UserService {
formData : UserData;
constructor(private http:HttpClient) {}
createUser(formData:UserData)
{
return this.http.post(API_URL+'/user/signup',formData);
}
}
and this is the the user.model class :-
export class UserData{
public Email:string;
public Password:string;
public Rera_no:string;
public Name:string;
public Company_name:string;
}
and i'm getting the following error :-
ERROR TypeError: "_co.service.formData is undefined"
can anybody tell me where i'm going wrong and how can i correct it ?
you are initializing with the Class object but not creating it's object though. So
do changes like this in your component
from
formData : UserData;
to
formData = new UserData();
in your template
<form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm">
<div class="form-group">
<input name="Name" class="form-control" #Name="ngModel" [(ngModel)]="service.formData?.Name" required>
</div>
</form>
I hope this wil solve your issue
EDIT
you are using Object variable as ngModel which is not created in the Service yet. so try to initialize it first with empty string.
export class UserData{
public Email:string;
public Password:string;
public Rera_no:string;
public Name: string = '';
public Company_name:string;
}
I think it is because you need to call method from service UserService in component with form AgentSignupComponent . So you need to call createUser method in AgentSignupComponent;
import { Component, OnInit } from '#angular/core';
import {UserService} from '../../shared/user.service';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-agent-signup',
templateUrl: './agent-signup.component.html',
styleUrls: ['./agent-signup.component.css']
})
export class AgentSignupComponent implements OnInit {
constructor(private service:UserService) { } //You use DI this but dont call method;
ngOnInit() {
}
signUp(form:NgForm) {
this.service.createUser(form);
}
}
Write a console.log(service); in your InOnInit() function of your AgentSignupComponent class. Observe what properties you can see in your console. This error means it cannot access the UserData object in your formData variable. So you need to initiate a UserData object and assign a value to the variable. Change formData : UserData; to formData = new UserData();

Categories

Resources