Parse Json from file - json

I have service to parse json
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class TestService {
private tsUrl = './../Test/test.json';
data: Object;
constructor(private http: Http) {}
getTest(): Observable<any> {
return this.http.get(this.tsUrl)
.map(res => res.json());
}
}
But When I call this in my component
private p: any;
constructor(private testService : TestService ) {
this.p =this.testService .getTest().subscribe(
data => {
console.log(data);
};
console.log(this.p);
}
it logs:
What can I do?
And am I doing parse from json file right? File path is correct
#echonax solved my problem but now I see this error message

Related

How can I access the first element of JSON array data?

I'm using ionic as a front end and Laravel as a back end.
This is the returned JSON data from an API URL, I want to access just the first element which is a.jpg without anything else, I tried using filenames.[0] but it's just displaying [ which means that it's calling the first character not the first element of the array.
Here's the JSON data:
[{"filenames":"[\"a.jpg\",\"b.jpg\",\"c.jpg\"]"}]
Here's my .ts file
import { ApiLandingRecipesService} from '../api-landing-recipes.service'
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.page.html',
styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
datauser: any[];
constructor( public api: ApiLandingRecipesService) { }
ngOnInit() {
this.getDataUser();
}
async getDataUser() {
await this.api.getDataUser()
.subscribe(res => {
console.log(res);
this.datauser =res;
console.log(this.datauser);
}, err => {
console.log(err);
});
}
and Here's my service file:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const apiUrl = "https://example.com/showimages";
#Injectable({
providedIn: 'root'
})
export class ApiLandingRecipesService {
constructor(private http: HttpClient) { }
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError('Something bad happened; please try again later.');
}
private extractData(res: Response) {
let body = res;
return body || [] ; }
getDataUser(): Observable<any> {
return this.http.get(apiUrl, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
}
It's because filenames is indeed a string (a json string representation of the array) and not an array.
Try converting the string into an array first.
JSON.parse(filenames)[0]
The value of filenames here is a string and not an array, which is why you're getting [ when you try to access the first element.
You probably need to parse the value, here's an example (assuming datauser) is the JSON data you've shown us.
let filename = JSON.parse(datauser[0].filenames)[0]

Ionic 3 RSS read with rss2json "Unprocessable Entity"

I'm having trouble converting RSS to JSON using the rrs2json API with Ionic 3. If I execute the code it gives me the error --> Response {_body: "{" status ":" error "," message ":" rss_url parameter is required."} ", Status: 422, ok: false, statusText:" Unprocessable Entity "}
Code:
noticies.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RssProvider } from '../../providers/rss/rss';
#IonicPage()
#Component({
selector: 'page-noticies',
templateUrl: 'noticies.html',
})
export class NoticiesPage {
rssDataArray: any = [];
constructor(public navCtrl: NavController, public navParams: NavParams, public rssProvider: RssProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad NoticiesPage');
this.Get_RSS_Data()
}
Get_RSS_Data(){
this.rssProvider.GetRSS().subscribe(
data => {
this.rssDataArray = data;
console.log(data);
}
);
}
}
providers --> rss --> rss.ts
import { Injectable } from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class RssProvider {
constructor(public http: Http) {
console.log('Hello RssProvider Provider');
}
GetRSS(){
const RSS_URL: any='http://rss.cnn.com/rss/edition.rss';
const API: any='XXXXXXXXXXXXXX';
const count: any =20;
const API_URL: any ='https://api.rss2json.com/v1/api.json';
const response = this.http.post(API_URL, {'rss_url': RSS_URL,'api_key': API, 'count': count}).map(res => res.json());
return response;
}
}
Error -->
Error
Alright. I registered myself with the rss2json service and made sure this solution actually works (you can see the data in console).
The issue you have is that you are not using a proper way to form http request with HttpParams.
Here is working stackblitz that uses my key: https://stackblitz.com/edit/ionic-jdwqjg
now some details:
when you configure a URL using rss2json it basically adds parameters to the original URL, example:
https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Ftechcrunch.com%2Ffeed%2F&api_key=q5ijkolkdjk3urzrcfaehxeoimxr3tdu5ieiqcrq&order_by=pubDate&order_dir=asc&count=20
So in Angular/Ionic you need to leverage Angular's HttpParams to properly form request, here is your provider code with HttpParams:
provider code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable()
export class RssProvider {
private API_URL: string;
constructor(public http: HttpClient) {
this.API_URL = "https://api.rss2json.com/v1/api.json";
}
GetRSS() {
const params = { params: new HttpParams().set('rss_url', 'http://rss.cnn.com/rss/edition.rss').set('api_key','q5ijkolkdjk3urzrcfaehxeoimxr3tdu5ieiqcrq').set('order_by', 'pubDate').set('order_dir', 'asc')
}
return this.http.get(this.API_URL, params);
}
}

How to get json file from HttpClient?

I am trying to get a json file from HttpClient, but I get a error when I add .subscribe
imports:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpClientModule } from '#angular/common/http';
import { HttpModule, Request, Response, Headers, Http } from '#angular/http';
import { Observable } from 'rxjs';
My code:
When I add .subscribe (yellow marked in image) I got the following error. What does it mean?
Object { _body: error, status: 0, ok: false, statusText: "", headers:
Object, type: 3, url: null }
If you want to make something very clear and organised you should create a service in angular and call the service from your component.
Like this for example:
Service.ts:
import { Injectable } from "#angular/core";
import { Observable, throwError } from "rxjs";
import {
HttpClient,
HttpHeaders,
HttpErrorResponse
} from "#angular/common/http";
import { catchError, map } from "rxjs/operators";
// Set the http options
const httpOptions = {
headers: new HttpHeaders({ "Content-Type": "application/json", "Authorization": "c31z" })
};
#Injectable({
providedIn: "root"
/**
* Service to call all the API
*/
export class ApiService {
constructor(private http: HttpClient) {}
/**
* Function to handle error when the server return an error
*
* #param error
*/
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error("An error occurred:", error.error.message);
} else {
// The backend returned an unsuccessful response code. The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// return an observable with a user-facing error message
return throwError(error);
}
/**
* Function to extract the data when the server return some
*
* #param res
*/
private extractData(res: Response) {
let body = res;
return body || {};
}
/**
* Function to GET what you want
*
* #param url
*/
public getListOfGroup(url: string): Observable<any> {
// Call the http GET
return this.http.get(url, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError)
);
}
}
Component.ts:
import { Component, OnInit } from "#angular/core";
import { ApiService } from "../../services/api.service";
#Component({
selector: "app-example",
templateUrl: "./example.component.html",
styleUrls: ["./example.component.css"]
})
export class ExampleComponent implements OnInit{
url = "/url/path/to/your/server";
constructor(private api: ApiService) {}
ngOnInit() {
this.api
.getListOfGroup(url)
.subscribe(
data => {
console.log(data);
},
err => {
console.log(err);
}
);
}
}
My advice would be to follow the getting start of angular if not you will be quickly lost. Service tutorial angular

Unexpected token < in JSON at position 0 when attempt call ASP.NET controller

I'm found and read many post about this error but don't found analogous or similar issues.
Attempt get data from MVC controller using post in angular 2.
Controller:
[RoutePrefix("")]
public class CategoryController : ApiController
{
[HttpPost, Route("createNode")]
public object CreateNode([FromBody]string nodeText)
{
return Json( new { nodeText = "test"});
}
}
function in component
onclickCreateFolder(categoryName: string) {
this.categoryService.createNode(categoryName).then(result => {
});
angular-2 service
import { Injectable } from '#angular/core';
import { Http, RequestOptions, Request, RequestMethod, Headers } from '#angular/http';
import { BaseService } from '../../base/base.service'
import { CategoryViewModel } from '../model/category-tree.model';
import { TreeNode } from 'primeng/primeng';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class CategoryTreeService {
private apiUrl: string = '/';
constructor(private baseService: BaseService, private http: Http) {
}
createNode(nodeText: string): Promise<any> {
return this.baseService.post(this.apiUrl + "createNode", JSON.stringify({nodeText}));
}
}
I am using base service. Here is a part that initiate post request:
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
import { Response, RequestOptionsArgs, ResponseContentType } from '#angular/http';
import { Http, RequestOptions, Request, RequestMethod, Headers } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
#Injectable()
export class BaseService {
private headers: Headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Data-Type': 'json' });
constructor(private http: Http, private router: Router) {
}
public post<T>(url: string, body: any, options?: RequestOptionsArgs): Promise<T> {
return this.http.post(url, body, this.mergeHeaders(options))
.toPromise()
.then(response => response.json() as T)
.catch(this.handleError.bind(this));
}
private mergeHeaders(options?: RequestOptionsArgs): RequestOptionsArgs {
let args = options || {};
args.headers = args.headers || this.headers;
return args;
}
public handleError(error: any) {
if (error.status == 400) {
switch (error.statusText) {
case "Authentication":
this.router.navigate(['/error/auth']);
break;
default:
return Promise.reject(error);
}
return;
}
return Promise.reject(error.toString());
}
}
I understand the reason for the error because in response i see my single html page. Also in debug i see that method in ASP.NET controller is not called. Maybe error in ASP.NET MVC routing?
Already spent a lot of time, but I still do not understand where the error is. What i'm doing wrong?

SyntaxError: Unexpected token < in JSON at position 3 in ionic 2

I'm having an error in Ionic 2 "SyntaxError: Unexpected token < in JSON at position 3". My json format is correctly structured using spring boot.
Below is my spring boot code.
Appreciate your help.
#RequestMapping(value="/myview", method=RequestMethod.GET, produces = "application/json")
#ResponseBody
List<Client> myView( #ModelAttribute("client") Client client){
List<Client> data=(List<Client>) clientService.getAll();
return data;
}
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PeopleService {
people: any;
constructor(public http: Http) {}
load(){
if (this.people) {
return Promise.resolve(this.people);
}
return new Promise(resolve => {
this.http.get('http://localhost:8080/myview')
.map((res)=>res.json()).subscribe((data)=>{
console.log(data);
this.people=data;
resolve(this.people);
}, err=>{console.log(err)});
});
}// end load function
}
JSON from /myview
[{"id":1,"username":"donald#yahoo.com","policy":"V121293031","name":"Donald","mobile":"0504735260","email":"dcgatan#gmail.com","address":"Dafza Dubai","amount":800.98,"datetimestamp":1472861297000},{"id":3,"username":"dcgatan78#gmail.com","policyno":"V38998933","fname":"Donald","mobile":"0501234567","email":"dcgatan#gmail.com","address":"MetDubai","amount":334.34,"datetimestamp":1472862939000},{"id":4,"username":"dcgatan#yahoo.com","policyno":"V34342323","fname":"Snoopy","mobile":"0501234567","email":"dcgatan#yahoo.com","address":"Metlife Dafza Dubai","amount":883.43,"datetimestamp":1472916463000}]
My http://localhost:8080/myview is not working because when I tried the below code with Array value it works. How to call the http instead of putting static values in the Array?
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PeopleService {
people: Array<any> = [{"id":1,"username":"donald#yahoo.com","policyno":"V121293031","fname":"Donald","mobile":"0504735250","email":"dcgatan#gmail.com","address":"Dafza Dubai","amount":800.98,"datetimestamp":1472861297000},{"id":3,"username":"dcgatan78#gmail.com","policyno":"V38998933","fname":"Donald","mobile":"0501234567","email":"dcgatan#gmail.com","address":"MetLife Dubai","amount":334.34,"datetimestamp":1472862939000}];
constructor(private http: Http) {}
load(){
if (this.people) {
return Promise.resolve(this.people);
}
return new Promise(resolve => {
this.http.get('http://localhost:8080/myview')
.map((res)=>res.json())
.subscribe((data)=>{
this.setPeople(data);
resolve(this.people);
});
});
}// end load function
setPeople(data) {
if (data) {
for (let id of Object.keys(data)) {
let item = data[id];
item.id = id;
this.people.push(item);
}
}
}
}
Your call to /myview would be returning incorrect json. It must be having HTML elements. Performing res.json() extracts data from _body of the response, if it's valid. But in your case it is throwing an error.