Display data from text file in html using httpclient - node.js

I am working on an angular project. I have a text file which that is red using node js. The content is then stored in a url. I need to apply an http get method to get the data from the server and display it on the client side.
I tried the following code but when I hit the button I don't get the file data displayed. What is the problem?
src/app/file.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class ConfigService {
constructor(private http: HttpClient) {}
getFile() {
return this.http.get('http://localhost:3000/hello');
}
}
src/app/app.component.html
<p>
<button (click)="getFile()">get data</button>
</p>

You have a few problems. First, you're not subscribing to the Observable, so nothing is going to happen. Second, you also need to handle the Observable, you're not. Third, you have not defined a place to inject the data once received.
...
#Injectable()
export class ConfigService {
data = {};
constructor(private http: HttpClient) { }
getFile() {
this.http.get('http://localhost:3000/hello').subscribe(result => {
this.data = result });
}
}
then you need somewhere to display it,
<p>
<button (click)="getFile()">get data</button>
<div *ngIf="data">{{ data }}</div>
</p>

Related

GET() communication between Angular and Node JS

I have an Angular and Node JS project with Typescript in which I am trying to create the communication between them using a service.
When making a get() request from the front I can't get anything from the back, I don't know what I might be missing to configure or what problem I have in the service.
This is the API response:
This is the service.ts:
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: 'root'
})
export class DashboardService {
private url = 'http://localhost:8080/list/product'
constructor(
private http: HttpClient
) {}
public getTest() {
return this.http.get(`${this.url}`);
}
}
This is the component.ts where I am trying to display the message on the console:
import { Component, OnInit } from '#angular/core';
import { DashboardService } from './dashboard.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
constructor(
private dashboardService: DashboardService
) {
}
ngOnInit() {
console.log('hola')
console.log(this.dashboardService.getTest().subscribe())
}
}
This is what I get on the console:
How should I do the GET() request to communicate with the back?
You are subscribing but then doing nothing with the subscription. I recomment you read up on angular subscriptions a bit more, but effectively what you want to do is get the result from the subscription like so.
items: string[];
this.dashboardService.getTest().subscribe({
next: result => items = result,
});
Also your get method in your service needs a bit of work.
public getTest(): Observable<string[]> {
return this.http.get<string[]>(`${this.url}`);
}
This is for returning a list of strings

How do I export a function in a class component into another page?

I want to change the text of a message in (Message.js) from 'Not Updated' to 'Updated' when a button on another page (PageButton.js) has been clicked.
Message.js
import React from 'react';
class Message extends React.Component {
constructor (){
super()
this.state = {
message: 'Not Updated'
}
}
changeMessage(){
this.setState =({
message: 'Updated'
}
)
}
render(){
return (
<h1>{this.state.message}</h1>
)
}
}
export default Message
Pagebutton.js
import React from 'react';
import { changeMessage } from "./Message"; //this does not work
import Message from "./Message"; //this does not work too
class Pagebutton extends React.Component {
render(){
return (
<div>
<button onClick={()=>this.changeMessage()}>Change Text</button>
</div>
)
}
}
export default Pagebutton;
In Pagebutton.js, 'changeMessage' is not defined, how do I make it work? If this way of importing functions is not correct, please teach me an alternative way of doing it :)
Thank you so much in advance for your help!
You can't export things inside functions or classes in javascript. In order to get access, you'd have to pass down changeMessage as a prop from a component that both Message and Pagebutton are descendants of. See: https://reactjs.org/docs/components-and-props.html
An example setup would be:
Container.js
import React from 'react';
import Pagebutton from "./Pagebutton";
import Message from "./Message";
class Container extends React.Component {
constructor (){
super()
this.state = {
message: 'Not Updated'
}
}
changeMessage(){
this.setState =({
message: 'Updated'
}
)
}
render(){
return (
<Message message={this.state.message} />
<Pagebutton changeMessage={this.changeMessage.bind(this)} />
)
}
}
export default Container
Pagebutton.js
import React from 'react';
class Pagebutton extends React.Component {
render(){
return (
<div>
<button onClick={()=>this.props.changeMessage()}>Change Text</button>
</div>
)
}
}
export default Pagebutton;
Message.js
import React from 'react';
class Message extends React.Component {
render(){
return (
<h1>{this.props.message}</h1>
)
}
}
export default Message
Addition to answer by #Kyruski, you can also use Context API, which enables "magically passing props".
https://reactjs.org/docs/context.html
Documentation has many examples, that you can try.

Displaying json Data into a list in angular using an array and httpClient

I am using Angular 8, to get JSON data and displaying it as a list, I do not know where I am wrong, as it's not displaying any error. And the view is empty. If anyone have a good eye or understands the logic. I just started angular and don't seem to find what is wrong.
video.service.ts
private _getUrl= "/api/videos";
constructor(private _http: HttpClient) { }
getVideos(){
return this._http.get(this._getUrl).pipe(map((response: any) => response.json()));
}
video.center.component.ts
#Component({
selector: 'app-video-center',
templateUrl: './video-center.component.html',
styleUrls: ['./video-center.component.css'],
providers: [VideoService]
})
videos = [];
constructor(private _videoService: VideoService) { }
ngOnInit(): void {
this._videoService.getVideos().subscribe(data => this.videos = data);
console.log("videos array", this.videos); // even this is not working !
}
video.list.component.html
<ul class="nav nav-pills nav-stacked">
<li (click)="onSelect(video)" *ngFor="let video of videos"><a>{{video.title}}</a></li>
</ul>
In Angular 4.3 the new HttpClient (#angular/common/http) was introduced in which the response object is json by default. So you don't need to map the answer.
So just return the http response:
private _getUrl= "/api/videos";
constructor(private _http: HttpClient) { }
getVideos(){
return this._http.get(this._getUrl);
}

binding data methods in react.js latest version

I have much experience in Angular. Just learned React.
Very curious about data binding methods in React.
I think the most effective method is to use ContextAPI.
ContextAPI is not to bind data in component, I think. It's just for sharing data across all levels of the application. Especially can be used to send data to the child components from parent component without passing all paths of DOM tree like when using props.
import React, { Component } from 'react';
class FormControl extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.handleChange = this.handleChange.bind(this); // binding this
}
handleChange({ target: { value }) {
this.setState({ value });
}
render() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
);
}
}
Or making the handleChange func with arrow func is also another way.
From v16.8, we can use React Hooks(like useState, useEffect, ...) to bind data..
See this link

"Get" request works (?) but not displaying data

I'm trying to do a crud with angular and node.
My rest API is completed (made with node and mysql);
Trying to display my JSON data at the HTML template, but I'm not being successful...
Thank you if you could help me :)
My service:
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { map } from "rxjs/operators";
import { Produto} from './produto';
import { catchError } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
#Injectable()
export class ProductService {
constructor(private _http : Http){ }
getProdutos(): Observable<Produto[]>{
return this._http
.get("http://localhost:8080/produtos").pipe(
map(res => res.json()));
}
}
Html:
<tr>
<th>Product</th>
<th>Price</th>
<th>Description</th>
<th>Category</th>
<th>Actions</th>
</tr>
<!-- Use *ngFor directive to loop throught our list of products. -->
<tr *ngFor="let produto of produtos">
<td>{{produto.nome}}</td>
<td>{{produto.descricao}}</td>
<td>{{produto.valor}}</td>
<td>{{produto.src}}</td>
<td>
Component
import { Component, OnInit, Input, Output, EventEmitter } from
'#angular/core';
import { ProductService } from '../product.service';
import { Observable } from 'rxjs';
import { Produto } from '../produto';
#Component({
selector: 'app-read-products',
templateUrl: './read-products.component.html',
styleUrls: ['./read-products.component.css'],
providers: [ProductService]
})
export class ReadProductsComponent implements OnInit {
produtos: Produto[];
constructor(private productService: ProductService){}
ngOnInit(){
this.productService.getProdutos()
.subscribe(produtos =>
this.produtos=produtos['records']
);
}
}
Class:
export class Produto {
constructor(
public produto_id: number,
public nome: string,
public descricao: string,
public valor: number,
public src: string
){}
}
My json response (when goes to the link):
[{"produto_id":10,"nome":"caderno","descricao":"maycon","valor":23.2212,"src":"aasssaa"}]
Have more classes in my project, if someone thinks that the problem is in another, just tell...
OBS: CREATED WITH ANGULAR CLI AND FOLLOWING THIS TUTORIAL
If you get un-named array from backend then you should assign result directly to productos :
this.productService.getProdutos()
.subscribe(produtos =>
this.produtos=produtos
);
If you get your array data here in productos then your HTML ngFor loop will work correctly :
<tr *ngFor="let produto of produtos">
<td>{{produto.nome}}</td>
<td>{{produto.descricao}}</td>
<td>{{produto.valor}}</td>
<td>{{produto.src}}</td>
<td>
</tr>
You should return the changed response inside map function. Like this
return this._http
.get("http://localhost:8080/produtos").pipe(
map(res =>
return res.json()));
}
Do a console.log to check whether you are receiving the data and identify the structure of the data. For the json response you have mentioned , in your component just assign it directly to the array
this.produtos=produtos;
Hope this helps.

Resources