How do i pass data received from angular to html front-end? - json

this is my angular service:
#Injectable()
export class ApiService {
private get_msg_url: string = "http://localhost:3000/getmessages";
constructor(private http:HttpClient) { }
getMessage(): Observable<IPosts> {
return this.http.post<IPosts>(this.get_msg_url,{"data":"data1"});
}
}
this is my message.component.ts :
export class MessagesComponent implements OnInit {
data = [];
iposts: IPosts[];
constructor(private apiSerivce: ApiService) {
}
getMessage(): void {
this.apiSerivce.getMessage()
.subscribe(data1 => this.data.push(data1));
}
ngOnInit(): void {
this.getMessage();
console.log(this.data);
}
}
this is my posts.ts:
export interface IPosts {
timestamp : number;
message_content : string;
message_link :string;
tags : string[] ;
}
this is messsage.component.html:
<p>Json data {{data}} </p>
whenever the code is run i can see the required data in console of chrome but there is no data shown on page.
the data received on console is of form:
[]
0:
message: Array(3)
0: {timestamp: 1522072833748,
tags: Array(2), _id: "5aacb7cc0281b558debacf26",
message_link:"String"
}}

the problem is, that you try to print an array, instead of the elements.
<p>Json data {{data}} </p>
change this to something like this:
<p *ngFor="let element of data; index as i">
Json data #{{i}}: {{element]]
</p>

As I can see, data is an array. you can display the raw content of an array with the pipe json : {{data | json}}
However I am not sur what you want to do with a json displayed in your html.

The problem is your output data is an array, not an element.
Try something like this,
<ul *ngFor="let element of data">
<li>{{element}}</li>
</ul>

Related

change url of HttpClient in angular when the language is changed

im trying to make a portfolio where when if someone wants changes the language in the menu the components change what json load for getting all data. I try to use BehaviourSubject and subject but i cant understand them so it difficult to use them. sorry for any mistake in english im learning
this is my service
export class PortfolioService {
language: string = 'espaniol';
constructor(private http: HttpClient) {}
obtenerDatos(): Observable<any> {
if (this.language === 'espaniol') {
return this.http.get('./assets/i18n/espaniol.json');
} else {
return this.http.get('./assets/i18n/english.json');
}
}
changeLang(value: string) {
this.language = value;
}
}
this is my header
export class HeaderComponent {
#Input() currentSection = 'section1';
siteLanguage = 'english';
languageList = [
{ code: 'english', label: 'English' },
{ code: 'espaniol', label: 'EspaƱol' },
];
constructor(private portfolioService: PortfolioService) {}
changeLang(localeCode: string) {
this.portfolioService.changeLang(localeCode);
}
scrollTo(section: string) {
document.querySelector('#' + section)!.scrollIntoView();
}
}
my template
<ng-container *ngFor="let language of languageList">
<li role="menuitem">
<a class="dropdown-item" (click)="changeLang(language.code)">
{{ language.label }}
</a>
</li>
</ng-container>
and my component that load the data
export class HomeComponent {
constructor(private datosPortfolio: PortfolioService) {}
miPortfolio: any;
ngOnInit(): void {
this.datosPortfolio.obtenerDatos().subscribe((data) => {
this.miPortfolio = data;
});
}
}
i tried to make a portfolio where i could change the language with a service that picked up when a changed happened in the header. the changed get picked up but the language is not changed in other components.
you need to wrap your data source observable with observable that changes when language changes. for that, the best is to use the BehaviorSubject.
take a look at this:
export class PortfolioService {
language = new BehaviorSubject<string>('espaniol');
constructor(private http: HttpClient) {}
obtenerDatos(): Observable<any> {
return this.language.asObservable().pipe(
switchMap(lang => this.http.get(`./assets/i18n/${lang}.json`))
)
}
changeLang(value: string) {
// update the value of this BehaviorSubject, and all
// subscribers notify about it
this.language.next(value);
}
}
this way every time language changed, new source emit in this.language BehaviorSubject and subscribe function fires again because of the new value, and them switch to other observable that makes the HTTP request with the language as a parameter that goes into the URL of the request.
hope it helps :)

Angular and JSON

I'm implementing a simple system to import JSON elements in Angular.
Everything works fine: I've used an interface, an observable and a directive. You can find the JSON here: http://jsonplaceholder.typicode.com/todos
Now, I want to use "completed", the boolean from JSON file, to display or not users when the page is loaded. There is a boolean "showUSer" and a method "displayUSer()" but I don't get it...
I cannot correctly retrieve this JSON data.
Any ideas ? :>
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
interface JSP {
"userId": string;
"id": string;
"title": string;
"completed": boolean
}
#Component({
selector: 'app-product',
template: `<div class="display" *ngFor="let todo of todos">
<div>User Id: {{todo.userId}}</div>
<div >id: {{todo.id}}</div>
<div *ngIf="showUser">Title: {{todo.title}}</div>
</div>`,
styles: ['.display {margin-top: 20px; margin-bottom: 20px;}']
})
export class ProductComponent implements OnInit {
title: string = "Products List";
todos: JSP[];
showUSer: boolean;
constructor(private http: HttpClient){
}
ngOnInit(){
this.http.get<JSP[]>('http://jsonplaceholder.typicode.com/todos')
.subscribe(result => this.todos = result);
}
displayUSer(): void {
this.showUSer = this.todos.completed;
}
}
Nitpicks: Your question says to display or not users but your code seems to be display or not the title. Also why do you capitalize the 'S' in 'USers'?
The problem is this function which seems to ignore your actual data layout:
displayUSer(): void {
this.showUSer = this.todos.completed;
}
todos is a property of your controller. This is an array from the api call you make and it doesn't contain a completed property, so this.todos.completed will always be false. I'm a little surprised that you don't get an error compiling your typescript.
It looks like you want this flag to be on a 'todo item' basis and not page-wide, so this.showUSer doesn't make sense. Also you don't seem to be calling displayUSer to set the value in any case.
Since you are looking at an individual todo item and the query is simple, why don't you just look at the flag?
<div *ngIf="todo.completed">Title: {{todo.title}}</div>
If you are wanting to set a page-wide flag based on some critieria, you can do that when you subscribe to the results. Here I'm assuming that you will set the showUSer flag if any of the todo items is marked as completed:
this.http.get<JSP[]>('http://jsonplaceholder.typicode.com/todos')
.subscribe(result => {
this.todos = result;
this.showUSers = result.reduce((previous, current) => previous || current.completed, false);
});
Your JSON hasn't any json.completed value, but json[_].completed.

How to list objects in an object in html?

I'm writing app in Angular and Node.js. I have an object (order) that has a list of objects (items) that also contain objects (list of product id). I want to display them all in an html file. Please help me.
html file:
<div *ngIf="order">
<div *ngFor="let item of order.items"> // <- it does not work
<a>{{order.items}}</a> // <--
</div>
</div>
ts file:
export class AdminOrderItemComponent implements OnInit {
order: Order;
orderId;
constructor(private orderService: OrderService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap
.subscribe(params => {
this.orderId = [params.get('id')];
this.getOrderById();
});
}
getOrderById() {
this.orderService.getOrderById(this.orderId).subscribe(
res => {
this.order = res;
},
err => console.log(err)
);
}
}
order interface:
export interface Order {
_id: any;
shipping: string;
userData: {};
sum: number;
items: {};
}
The ngFor iterates over the items of a collection. If you take a look at your model, you will realize that items is an object ({}), not an array ([]).
Your best bet is transforming the object received from your node.js backend to match your needs or (preferably I think) make your node.js model treat items as a collection as well which seems more appropriate.
Answer from #kg99:
Key: {{item.key}} and Value: {{item.value}}

Json data not rendering my html grid table

I can't able to render my html grid table in angular using json data that is from mysql database.Please someone help me.
Output of the angular code
export class UserlistComponent implements OnInit {
users: Observable<User[]>;
constructor(private _service:NgserviceService, private _route:Router) { }
ngOnInit() {
this.reloadData();
}
reloadData(){
this.users = this._service.getUserList();
}
}
It seems you receive an array and not an object. You could simply map the received data and keep the rest.
reloadData() {
this.users = this._service.getUserList().pipe(
map(arrayUsers => arrayUsers.map(arrayUser => ({
id: arrayUser[0],
email: arrayUser[1],
firstname: arrayUser[2],
lastname: arrayUser[3],
})))
);
}
Your output seems to be CSV kind (array of an array) not the JSON. So, you need to use {{user[1]}} for email instead of {{user.email}} and {{user[2]}} for firstname instead of {{user.firstname}}

How do I pass data from a json file into a html file in Angular 2?

I have this files.
wordCloud.ts
export class HomePageComponent {
wordcloudData : Array<string>;
private searchField : string;
private wordsApi : string;
wordClouds: any[] = [];
errorMessage: string;
listId:any = 1;
#Input() data : any;
#Input() testProperty : any;
#Input() dataField : string;
#Input() apiUrl : string;
constructor(public wordCloudListService: LexiconListService) {}
getWordCloudList() {
this.wordCloudListService.get('/assets/adhoc-search.json')
.subscribe(
wordClouds => {
EmitterService.get(this.listId).emit(wordClouds);
},
error => this.errorMessage = <any>error
);
}
ngOnInit() {
this.getWordCloudList();
EmitterService.get(this.listId).subscribe((wordClouds:any) => {this.wordClouds});
}
}
wordCloud.html
<div class="center" style="margin: 0 auto; width: 30%; padding-top: 100px;">
<cst-word-cloud [data]="{{wordClouds}}"></cst-word-cloud>
</div>
As you can see, I'm trying to load a json data and display the data into the wordCloud hmtl. I'm currently having difficulties doing this? Is there anything I'm doing wrong? How do I pass the value in the wordClouds array to display it?
In your ngOnInit() you are not getting the data of wordClouds in this.wordClouds.. just do this.
ngOnInit() {
this.getWordCloudList();
EmitterService.get(this.listId)
.subscribe((wordClouds:any) => {
this.wordClouds = wordClouds;
});
}
Do not emit the data. First of all is emitting a data is not the right approach. You should always emit the states like Boolean values or data which is used for a temporary basis. I would prefer not emitting the data, instead store first. Store it in some dataStore/ Class file. Make a class and store the data in it. After storing bind the template from that class getter method.