getting json data in realtime angular - json

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

Related

Cannot read queryParams in Angular

I am trying to fetch queryParams from url with window.location but query params are not being grabbed.
Example my url is www.abc.com?accountId=123#
I am looking for a way to grab accountId=123 as a queryParam or atleast the entire url.
When I used window.location I am getting www.abc.com/#/ instead of www.abc.com?accountId=123#
Why am I not able to read the query params?
Why am I not able to read the query params?
according to the angular documentation you can fetch the query parameters with the activatedRoute in Angular.
In the below example we grab a query parameter "name".
constructor(
private route: ActivatedRoute,
) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.name = params['name'];
});
}

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' });
}

getting empty data from api

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

Receiving JSON-Data via http: empty response

I'm new to Angular2 and somehow it's really hard to me to understand how http works in Angular2. I made a simple component which should display a json response. It doesn't work and I have no idea why. I checked many tutorials and tried it with promises as well as observables. Doesn't work. I just can't get the data of the response.
My code:
private doAction() {
this.doHttpRequest().subscribe(
data => this.content = data
);
this.content = JSON.stringify(this.content);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.catch(this.handleError);
}
this.content is bind to my template. When I click a button to start doAction() for a second I see "" in the template, after another second [object Object]
What is the problem here?
That's the expected behavior
private doAction() {
// schedule HTTP call to server and subscribe to get notified when data arrives
this.doHttpRequest().subscribe(
// gets called by the observable when the response from the server aarives
data => this.content = data
);
// execute immediately before the call to the server was even sent
this.content = JSON.stringify(this.content);
}
To fix it change it to
private doAction() {
this.doHttpRequest().subscribe(
data => {
//this.content = data;
this.content = data.json());
});
);
}
If you want code to be executed after data arrived, then you need to move it inside the subscribe(...) callback.
Since http requests are asynchron you have to put all your logic depending on the results of the http call in the subscribe() callback like this:
private doAction() {
this.doHttpRequest().subscribe(
data => {
this.content = data;
// any more logic must sit in here
}
);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json());
.catch(this.handleError);
}
Http call is returning data since it shows "[object Object]" in template. If you want to see the json data in template you can use the json pipe as below.
{{content | json}}
PS: No need of "this.content = JSON.stringify(this.content);" in your code.

use angular 2 data from rest api

I'm begining in Angular 2 , in the first I try to get data from JSON file and show it on a table and that's done , now I want to get data from rest api so I create my Restful webservices from Entity classes , I generate the CrossOriginResourceSharingFilter ( I use netbeans and glassfish) and I get the link with JSON output , I replace the link in the api url in angular 2 but it doesn't work
this in my Angular 2 employes.service
#Injectable()
export class EmployesService {
private empsUrl = 'localhost:25176/WebApplication4/app/employes'; // URL to web api
constructor(private http: Http) { }
getEmployes (){
return this.http.get(this.empUrl)
.map(res=> res.json())
.catch(this.handleError);
}
this is my employes.component
export class EmployesComponent implements OnInit{
emps: Employe[];
error: any;
mode = 'Observable';
errorMessage :string;
constructor(private empService: EmployesService,private _elRef :ElementRef) { }
getEmployes() {
this.empService.getEmployes()
.subscribe(
employes => this.emps = employes,
error => this.errorMessage = <any>error);
}
ngOnInit() {
this.getEmployes();
this is my console Errors
zone.js:101 XMLHttpRequest cannot load localhost:25176/WebApplication4/app/employes. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
thank you for helping