How to fetch json data in Angular 2+ - javascript

I'm trying to display a list with data fetched from a local json file. Here is how my service looks so far.
category.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
#Injectable()
export class CategoryService {
constructor(private _http: Http) { }
getCategories() {
return this._http.get('api/categories.json')
.map((response: Response) => response.json())
.do(data => console.log('All; ' + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || 'Server error');
}
}
here is how the Category Menu component where I inject it looks so far
import { Component, OnInit } from '#angular/core';
import { CategoryService } from '../category.service';
#Component({
selector: 'app-category-menu',
templateUrl: './category-menu.component.html',
styleUrls: ['./category-menu.component.css']
})
export class CategoryMenuComponent implements OnInit {
errorMessage: string;
commerceName= `El baratón`;
categoryName = `Bebidas`;
categories: any = 'Not assigned yet';
hasMenu?= true;
constructor(private _categoryService: CategoryService) { }
ngOnInit() {
return this._categoryService.getCategories()
.subscribe(
categories => this.categories = categories,
error => this.errorMessage = error
);
}
}
Now, the error I am getting in the console is a 404. For this project I have used the CLI version 1.0 and the categories.json file inside of the src/api/categories.json folder.
What am I doing wrong here?

move your api/categories.json to assets folder, then change url to
return this._http.get('/assets/api/categories.json')

Related

Angular returns data from an API call as [Object Object], but undefined in the component

I'm working on a project, and have come to a huge blocking point.
As I mentioned in my question, I've built a dataService, but my dataService shows the response properly, but it comes up as undefined in my Component.
Here's my code for the data.service.ts file
import { Injectable, OnInit } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import {
Http,
Response,
Request,
RequestOptions,
Headers
} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import { Institution } from './institution';
import 'rxjs/Rx';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
#Injectable()
export class DataService {
constructor(private http: HttpClient) { }
institutionData: Object;
//private http: Http;
grabInstitutionData(): Observable<Institution[]> {
return this.http
.get(`http://127.0.0.1:8000/courses/api/institution/list/`)
.map((response: Response) => {
console.log(response);
this.institutionData = <Institution[]>response.json();
console.log('this is right' + this.institutionData);
return this.institutionData;
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}
And my code for the Component File:
import { async } from '#angular/core/testing';
import { Component, OnInit } from '#angular/core';
import { DataService } from '../data.service';
import {Http, Response} from '#angular/http';
import { HttpClient } from '#angular/common/http';
import { Institution } from '../institution';
#Component({
selector: 'app-institutions',
templateUrl: './institutions.component.html',
styleUrls: ['./institutions.component.css']
})
export class InstitutionsComponent implements OnInit {
institutionData: Object;
_InstitutionsArray: Institution[];
constructor(private http: Http, private dataService: DataService) { }
getInstitutions(): void {
this.dataService.grabInstitutionData()
.subscribe(
resultArray => this._InstitutionsArray = resultArray,
error => console.log("Error :: " + error)
);
}
ngOnInit(): void {
this.getInstitutions();
}
}
I know its related to something pertaining to the asynchronous function call, but I can't exactly figure out what it would be.
Any and all help would be appreciated.
El-Teezus, not use map and not use json(). When we use "map" is for transform the response, It have not sense in your code
//In our service
grabInstitutionData(): Observable<Institution[]> {
return this.http
.get(`http://127.0.0.1:8000/courses/api/institution/list/`)
.do(response:Response)=>{
console.log(response);
this.institutionData = <Institution[]>response;
console.log('this is right' + this.institutionData);
})
.catch(this.handleError);
}
See that we use "do" to do "something" with the response without change it. Yes, "do" is to check if a respone is the respone expected or not or to cache the result anyway.
See too that we don't need write response.json(). HttpClient make it for us.
In your component
getInstitutions(): void {
this.dataService.grabInstitutionData()
.subscribe(
(resultArray) =>
{
this._InstitutionsArray = resultArray
//here you have the data
console.log(this._Institutionsrray);
},
(error) => console.log("Error :: " + error)
);
}

GET http://localhost:4200/api/x.json 404 (Not Found) - angular 2

Hello, There is a problem with a project that does not recognize a json file - and I do not know why. Is there anything I need to change or make it work?
this is my folders:
this is my service:
import { Injectable } from "#angular/core";
import { Ibrides } from "./brides";
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
#Injectable()
export class brideService {
private _brideUrl = 'api/brides.json';
constructor(private _http: HttpClient) { };
getBrides(): Observable<Ibrides[]> {
return this._http.get<Ibrides[]>(this._brideUrl)
.do(data => console.log('All:' + JSON.stringify(data)))
.catch(this.handleError)
}
private handleError(err: HttpErrorResponse) {
console.log(err.message);
return Observable.throw(err.message);
}
}
this is my component
import { Component, OnInit } from '#angular/core';
import { Ibrides } from "./brides";
import { brideService } from "./brides.service"
#Component({
selector: 'pm-brides',
templateUrl: './brides_list.component.html',
styleUrls: []
})
export class bridesListComponent implements OnInit {
constructor(private _brideService: brideService) {
}
errorMessage: string;
brides: Ibrides[] = [];
ngOnInit(): void {
this._brideService.getBrides()
.subscribe(brides => {
this.brides = brides
},
error => this.errorMessage = <any>error);
}
}
Just reference the file from the root level like this:
_brideUrl = 'app/api/brides.json'
For more information you can refer to this.

wordpress and angular theme update post list on when new post is published

Hi i'm new in Angular 4 and I want to use it to build a WordPress theme using the wp-api. I start with the ng-wp-theme but I and all its working fine, but I need that hen a new post is publish the post list page updates itself without reload the page. I saw some tutorials about the http services in angular but I dont find any solution to this, maybe its a Wordpress api issue and not the Angular part.
here is the service:
import { Injectable } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Observable } from 'rxjs/Observable';
import { Post } from './post';
import { environment } from '../../environments/environment';
#Injectable()
export class PostsService {
private _wpBase = environment.wpBase;
constructor(private http: HttpClient) { }
getPosts(): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + 'posts');
}
getPost(slug: string): Observable<Post[]> {
return this.http.get<Post[]>(this._wpBase + `posts?slug=${slug}`);
}
}
and the controller:
import { Component, OnInit } from '#angular/core';
import { Post } from '../post';
import { PostsService } from '../posts.service';
import { Router } from '#angular/router';
import { HttpErrorResponse } from '#angular/common/http';
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
providers: [PostsService]
})
export class PostListComponent implements OnInit {
public posts: Post[];
constructor( private postsService: PostsService, private router: Router ) {}
ngOnInit() {
this.postsService.getPosts().subscribe(
(posts: Post[]) => this.posts = posts,
(err: HttpErrorResponse) => err.error instanceof Error ? console.log('An error occurred:', err.error.message) : console.log(`Backend returned code ${err.status}, body was: ${err.error}`));
}
selectPost(slug) {
this.router.navigate([slug]);
}
}

Unable to retrieve JSON file in Angular 2 project

I am trying to display static JSON data in my angular 2 project. I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages.
service.ts
import { Injectable } from '#angular/core';
import { ConfigurationService } from '../../configuration.service';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs';
import { ListItem } from './list-item';
#Injectable()
export class DataService {
constructor(
private _http: Http,
private _configurationService: ConfigurationService
) {}
get() : Observable<ListItem[]> {
return this._http.get("app/data/MOCK_DATA.json")
.map((response: Response) => <ListItem[]> response.json())
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { DataService } from '../data.service';
import { ListItem } from './list-item';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-component',
templateUrl: 'component.html',
styleUrls: ['component.css']
})
export class Component implements OnInit {
busy:Subscription;
datas: ListItem[] = [];
constructor(
private _dataService: DataService,
private _confirmationService: ConfirmationService,
private _authService: AuthService,
private _router: Router,
) {
}
ngOnInit(){
}
getdatas() {
this.busy =
this._dataService.get()
.subscribe(data => this.datas = data)
}
Since it is static. there is no need to http.get.
Create a json.ts file
export your JSON file as
export const json={
"key":"value"
}
then import it where required
import { json } from './json.ts'
then console.log(json) inside the class to check the file/json.

How to display JSON objects in Angular2 views

New to Angular and I have the JSON available to me in the console. So the backend/REST call is functioning correctly. However I'm struggling to understand how to show the JSON in the view for the component.
Console screenshot:
app.component.ts
import { Component } from 'angular2/core';
import { TradeshowComponent } from './tradeshow/tradeshow.component';
#Component({
selector: 'app-container'
})
export class AppComponent {
constructor() { }
}
tradeshow.component.ts
import { Component, View } from 'angular2/core';
import { CORE_DIRECTIVES, NgIf, NgFor } from 'angular2/common';
import { DataService } from '../shared/services/data.service';
import { DashboardLayoutComponent } from '../dashboard_layout/dashboard_layout.component';
import { HTTP_PROVIDERS } from 'angular2/http';
#Component({
selector: 'tradeshow',
providers: [DataService, HTTP_PROVIDERS]
})
#View({
templateUrl: 'src/app/tradeshow/tradeshow.component.html',
directives: [DashboardLayoutComponent, NgIf, NgFor]
})
export class TradeshowComponent {
constructor(private _dataService: DataService) { this.getTradeShows() }
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeShows = tradeshows
error => console.error('Error: ' + err)
);
}
}
And the HTML I'm using is:
tradeshow.component.html
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
And my service looks like this:
data.service.ts
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Config} from '../../config/config';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class DataService {
// API path
baseUrl: string = '/api';
authUrl: string;
apiUrl: string;
registerUrl: string;
constructor(private _http: Http, private _config: Config) {
this.apiUrl = this._config.get('apiUrl') + this.baseUrl;
this.authUrl = this._config.get('apiUrl') + '/auth';
this.registerUrl = this._config.get('apiUrl') + '/register';
}
getTradeShows() {
return this._http.get(this.getApiUrl('/tradeshow/list'))
.map((res: Response) => res.json())
.catch(this.handleError);
}
}
This looks like a bug
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.getTradeShows() = tradeshows,
error => console.error('Error: ' + err)
);
}
it should be
getTradeShows() {
this._dataService.getTradeShows()
.subscribe(
tradeshows => this.tradeshows = tradeshows
error => console.error('Error: ' + err)
);
}
You can remove NgIf, NgFor from
directives: [DashboardLayoutComponent, NgIf, NgFor]
these are now globally available.
Change
<div *ngFor="#tradeshows of tradeshows">{{ tradeshows.name }}</div>
to
<div *ngFor="#tradeshow of tradeshows">{{ tradeshow.name }}</div>
#Child() was removed a while ago
})
#View({
should be replaced by ,
I made an error in this line
tradeshows => this.tradeShows = tradeshows
should be (lowercase S)
tradeshows => this.tradeshows = tradeshows
Plunker example

Categories