getting empty data from api - json

I'm trying to get data from an api. Although I'm able to get data from json placeholder api and also from a dummy json data i created, I'm not ablt to fetch from the backend api. When i try to get data from json placeholder, it concoles the data but shows and emty array when i try to fetch it from the backend api. And its not empty either.
component.ts
allUsers: UserCreation[];
constructor(private userService: UserCreationService) { }
getUsersFromServices():void{
this.userService.getUsers().subscribe(
(Users)=>{
this.allUsers=Users;
console.log(`this.allUsers = ${JSON.stringify(this.allUsers)}`);
}
)
}
ngOnInit(): void {
this.getUsersFromServices();
}
service.ts
constructor(private http:HttpClient) { }
private usersUrl='https://jsonplaceholder.typicode.com/users';
getUsers():Observable<UserCreation[]>{
return this.http.get<UserCreation[]>(this.usersUrl).pipe(
tap(receivedUsers
=>console.log(`receivedUsers=${JSON.stringify(receivedUsers)}`)),
catchError(error=>of([]))
);
}
console when fetching json placeholder data
console while fetching api data

Related

Typescript (Angular) - JSON model Deserialisation

I would like to add and populate additional fields (which are not sent by backend service) in my http model. Catch is that I am not able to populate (map) those fields in the place where http response is being received since I am using internal framework.
Is there a possibility in Typescript (Angular) to somehow override JSON Deserialisation flow/Instance creation and populate mentioned fields. For example:
interface ElectricDevice {
energy_meter_start: number; // received from backend service
energy_meter_stop: number; // received from backend service
energy_spent: number; // not received by backend service, but needs to be populated as energy_meter_stop - energy_meter_start
// ...
/* I would like to somehow populate energy_spent as energy_meter_stop-energy_meter_end on instance creation (deserialisation) */
}
You need a HttpInterceptor, in which you can manipulate data.
#Injectable()
export class CustomJsonInterceptor implements HttpInterceptor {
constructor(private jsonParser: JsonParser) {}
intercept(httpRequest: HttpRequest<any>, next: HttpHandler) {
if (httpRequest.responseType === 'json') {
// If the expected response type is JSON then handle it here.
return this.handleJsonResponse(httpRequest, next);
} else {
return next.handle(httpRequest);
}
}
Read more about it in the tutorials: https://angular.io/api/common/http/HttpInterceptor
I have asked you for the especific names of your services.
But, in the meantime, I give you a 'general' answer to your question.
You just need to do this:
this.yourService.yourGetElectriceDevices
.pipe(
map (_resp: ElectricDevice => _resp.energy_spent = _resp.energy_meter_stop - _resp.energy_meter_start
)
.subscribe( resp => { //your treatment to the response });
This above, only works for a rapid test.
If you want to do somethig more 'elaborated', you could transform your interface into a class, and add your calculated attribute, something like this:
export interface ElectricDevice {
energy_meter_start: number; // received from backend service
energy_meter_stop: number; // received from backend service
}
export Class ElectricDeviceClass {
energy_meter_start: number;
energy_meter_stop: number;
energy_spent: number;
constructor (data: ElectricDevice) {
this.energy_meter_start = data.energy_meter_start;
this.energy_meter_stop= data.energy_meter_stop;
this.energy_spent = this.energy_meter_stop - this.energy_meter_start;
}
And for using it, just:
import { ElectricDeviceClass, ElectricDevice } from './../model/...' // There where you have yours interfaces and model classes
this.yourService.yourGetElectriceDevices
.pipe(
map (_resp: ElectricDevice => new ElectricDeviceClass(_resp)
)
.subscribe( resp => { //your treatment to the response });

How to handle if API response is a string instead of JSON in Ionic + Angular

If response coming from my API is in JSON format then it works fine but if in non-json format then the function does not work. Here is what I am doing -
In my page.ts
import { ApiconnectService } from '../../apiconnect.service';
export class BinaryGraphPage implements OnInit {
value : any;
constructor(
private cs: ApiconnectService
) { }
userGraph(){
this.cs.unilevelGraph().subscribe(response =>{
this.value = response;
})
}
}
In apiconnect.service.ts
unilevelGraph(){
return this.http.get(this.url+'?sponser='+uid);
}
The response coming from API is not in JSON format (I tried JSON format and it works fine but for some reason my response need to be in text/string).
In API, response is a long text and contains html tags such as br tag, span and li tag e.g.: Howdy user, this is your graph list 1.item, 2. item, 3.item, etc.
Since response is not in JSON format, so this errors appear in my console. Error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://......
Can you please suggest me how to rewrite the function userGraph() so that it can work with string or text.
Since you are not getting a JSON response, specify the response type in the options. So, the service method becomes:
unilevelGraph(){
return this.http.get((this.url+'?sponser='+uid), { responseType: 'text' });
}

TypeScript fetch data from API

I want the code below to be able to fetch JSON data from a simple API I have set up.
export class FaqFakeDb
{
public static data = fetch('https://#######.co.uk/api/faq/');
}
This is for a FAQ page and its meant to be pulling data from the API. I am new to typescript and Angular so forgive me if I've made a simple mistake.
I want it to function like this:
export class FaqFakeDb
{
public static data = [
{
"id":"1",
"question":"test1",
"answer":"test1"
},
{
"id":"2",
"question":"test1",
"answer":"test1"
},
{
"id":"3",
"question":"test1",
"answer":"test1"
}
];
}
Any help will me much appretiated :)
fetch returns a promise, so data will be a promise. Any time you want to access data you will have to use async/await or .then or something else to handle promises. You also don't have any error handling in case your API call fails.
One example of how you could handle this would be:
async ngOnInit() {
try {
const response = await FaqFakeDb.data;
this.quesitons = await response.json();
} catch {
// fetch encountered an error; you can handle it here.
}
}
However, I would recommend that you use Angular's built in HttpClientModule instead and make the API call as it's needed (in the component that needs it) rather than when an arbitrary class is declared.

getting json data in realtime angular

I have a URL with data in json format and I get it with the HttpClient and it works good.
I binded the function
showConfig()
to get the data to a button and when pressed I get the newest data.
BUT: I have to click again to get the newest data.
Can I make it refresh automatically, like with Firebase?
url = myURL;
constructor(private http: HttpClient) { }
getConfig() {
return this.http.get(this.url);
}
showConfig(){
this.getConfig().subscribe(data => console.log(data))
}
an

Ionic2 and get Json

I am trying to use Ionic2 and I made a service to fetch a local stored Json.
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
#Injectable()
export class Page1Service {
public constructor(private _http: Http) {}
public GetItems() {
return this._http.get('/app/Ressources/Items.json').map((response: Response) => response.json().data);
}
public PrintJson():boolean {
var myresult;
this.GetItems().subscribe((result) => {
myresult = result;
console.log(result);
});
}
I also a made PrintJson() method that just print the json for test purpose.I got the error:
GET http://localhost:8100/app/Ressources/slides.json 404 (Not Found)
I don't get why. And I can't find an easy and uptodate tutorial. Or should I use fetch()?
First copy your json to the following dir(you can create the folder "data"):
[appname]/www/data/data.json
Type in the following command in your console:
ionic g provider JsonData
It should create a provider for you.Go to that page and enter the following in load() function:
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.get('data/data.json').subscribe(res => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
this.data = res.json();
resolve(this.data);
console.log(this.data);
});
});
}
I usually create an Observable wrapped around the api-call like this:
public GetItems() {
return Observable.create(observer => {
this._http.get('/app/Ressources/Items.json').map(res =>res.json()).subscribe(data=>{
observer.next(data)
observer.complete();
});
});
}
Then I have to subscribe on that method in order to get the results and do something with it. (You could be to delegate the result to a list in the GUI)
GetItems().subscribe(data=>{
myResult = data;
});
EDIT: It might help to put this in the class as well
export class MyClass{
static get parameters(){
return [[Http]];
}
}
Just try to get the response.json() rather than response.json().data in GetItems() method
The issue is because of different paths of json files in local browser(computer) and device (android). Create data folder inside the src\assets folder. Move your json file into that.
When we run ionic serve, it will move that folder (with file) into www\assets folder. Then do following things:
Import Platform service of ionic2
import { Platform } from 'ionic-angular';
Inject Platform Service.
constructor(private http: Http, private platform: Platform ) { }
Use Platform Service.
public getItems() {
var url = 'assets/data/Items.json';
if (this.platform.is('cordova') && this.platform.is('android')) {
url = "/android_asset/www/" + url;
}
return this.http.get(url)
.map((res) => {
return res.json()
});
}