I am trying to pull data from a json file and display it, but I am unable to proceed with the program because I lack experience in coding Angular.
Currently using Angular 4.3, which uses HttpClientModule.
app.component.ts
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('/src/app/students.json')
}
chgTab1() {
this.title = "Changed Title";
}
chgTab2() {
//Want to display the items from json file
}
}
students.json
[
{"id": "3", "mame": "Dama"},
{"id": "1", "mame": "ASD"},
{"id": "2", "mame": "Chris"},
{"id": "4", "mame": "Sass"},
]
import { Component, OnInit } from '#angular/core';
import { Http,Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
showData = false;
constructor(private http: Http) { }
ngOnInit(): void {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.get('/assets/students.json', { headers: headers }).map(res => res.json()).subscribe(data => {
this.data = data;
})
}
chgTab1(){
this.title ="Changed Title";
}
chgTab2(){
//Want to display the items from json file
this.showData = !this.showData;
}
}
I have edited the whole thing. It will now work for you. Ensure you have the path to your student.json in the correct place.I moved it to the assets directory
Related
How show to link: localhost:4200/navigator?nameA - this is json data?
I have box.json, if click getBox() - need move on link localhost:4200/navigator?nameA and show namA, box, first.If will be nameB - to need move on link localhost:4200/navigator?nameB.
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class BoxService {
constructor(private http: HttpClient) {}
getBox(): Observable<Object> {
return this.http.get('/assets/data/box.json');
}
}
////
import { Component, OnInit } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { BoxService } from './box.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
box$:any;
constructor(private boxService: BoxService){}
getBox() {
this.box$ = this.boxService.getBox();
console.log(this.box$);
}
}
//
[
{
"nameA": "1A",
"title":"1 Hi",
"rum": [{"box":"box1", "first": "1first-box"}]
},
{
"nameA": "2A",
"title":"2 Hi",
"rum": [{"2box":"box2", "first": "2first-box"}]
},
{
"name": "B",
"title":"2 Hi"
}
]
<button (click)="getBox()">Get box</button>
<ul>
<li *ngFor="let a of box$ | async; index as i">{{ a.nameA }}
<div *ngFor="let y of a.rum ">
nameA: {{ y.box }}/{{y.first}}
</div>
</li>
</ul>
This is my home.component.ts file:
import { Component, OnInit } from '#angular/core';
import {HttpClient, HttpResponse, HttpHeaders} from '#angular/common/http';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) { }
cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res.json();
}
)
}
ngOnInit() {
this.fetchData();
}
}
home.component.html file:
<h1>Cars</h1>
<table>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<tr *ngFor="let car of cars">
<td>{{car.id}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
</tr>
</table>
and cars.json file:
{
"cars": [
{
"id": 1,
"brand": "Seat",
"model" : "Leon"
},
{
"id": 2,
"brand": "Mercedes",
"model" : "AMG"
}
]
}
I started the json server and compiled the project. The outcome is just the table structure without the fetched data. The json server is listening on the 3000 port and i'm using angular 7.0.3 version. Can somebody help me?
Try this:
const fs = require('fs');
let rawdata = fs.readFileSync('cars.json');
let cars = JSON.parse(rawdata);
or
const mycars = JSON.stringify(rawdata);
console.log(mycars);
cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res;
}
)
}
This fixed my problem. Thank you for the help.
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class BackendService {
constructor() { }
setUser(formData) {
let fackresponce3 = {
" errorCode " : "1",
"errorMessage" : "User Created",
"rowCount" : "30",
"data" :{
"token" : "abcd"
}
};
let fackresponce1 = {
" errorCode " : "0",
"errorMessage" : "Some Error",
"rowCount" : "30",
"data" :{
"token" : "abcd"
}
};
return Observable.create(
observer => {
setTimeout ( () => {
observer.next( fackresponce3)
}
,2000)
});
}
}
You can use the of operator to create a new observable. Then pipe that observable and use the delay operator instead of the setTimeout.
https://www.learnrxjs.io/operators/creation/of.html
https://www.learnrxjs.io/operators/utility/delay.html
// backend.service.ts
import { of, delay, Observable } from 'rxjs';
export interface IResponse{
data: string;
}
#Injectable({
providedIn: 'root'
})
export class BackendService {
constructor() { }
setUser(formData?:any): Observable<IResponse> {
const fakeData = {} as IResponse;
return of(fakeData).pipe(delay(2000));
}
}
// note observables do not fire until they are subscribed to... so you can use it as follows
// app.component.ts
import { Component, Subscription, OnInit, OnDestroy } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private backendService: BackendService){}
ngOnInit(){
this.subscription = this.backendService
.setUser()
.subscribe(data => console.log(data));
}
ngOnDestroy(){
// also note to unsubscribe OnDestroy otherwise you will end up with a memory leak
this.subscription.unsubscribe();
}
}
// app.module.ts
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
providers: [ BackendService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Hello I am trying to import http call from '#angular/common/http' and am getting error message that module has no exported member 'http'
Error:[ts] Module '"e:/car/node_modules/#angular/common/http"' has no exported member 'Http'. [2305]
import {
RouterModule
} from '#angular/router';
import {
BrowserModule
} from '#angular/platform-browser';
import {
NgModule
} from '#angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
HomeComponent
} from './home/home.component';
import {
HttpClientModule
} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([{
path: '',
component: HomeComponent
}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
import {
Http
} from '#angular/common/http';
import {
Component,
OnInit
} from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) {}
products = [];
fetchData = function() {
this.http.get('http://localhost:5555/products').subscribe(
(res: Response) => {
this.products = res.json();
}
);
};
ngOnInit() {
this.fetchData();
}
}
the below code is used for inserting json file which includes the details
HttpClientModule will inject HttpClient service not the Http.
Please use HttpClient in constructor injection in the HomeComponent.
constructor(private http: HttpClient) {}
For Reference created sample stackblitz code.
I am trying to setup a mean stack crud application. The routes and the functionality is setup and tested using postman. I am getting correct responses for all the routes. Now I am trying to add the view part where the routes are called internally by the Angular application. I am trying to setup a basic get route. Following is my component code:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
users: {};
constructor(private userService: UserService) { }
ngOnInit() {
this.getUsers();
}
getUsers() {
this.userService.getAllUsers().subscribe(data => this.users = data);
}
}
and the service contains the following code:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
constructor(private http: Http) { }
getAllUsers() {
this.http.get('/api/users')
.map(res => res.json());
}
}
A sample response of the route using postman is as follows:
{
"status": true,
"err": null,
"data": [
{
"_id": "59d5db344c46e83a14b94616",
"name": "test"
},
{
"_id": "59d5db3c4c46e83a14b94617",
"name": "hello"
}
]
}
It always telling me the following error:
Property 'subscribe' does not exist on type 'void'.
What am I doing wrong? Can someone point me the standard way to do this?
Try this :
You forgot to return in your getAllUsers()
getAllUsers() {
return this.http.get('/api/users')
.map(res => res.json());
}