Unable to read JSON returned from API trying Angular2 - json

Unable to read the JSON returned from an API call.
Here is my Services File.
import { Injectable } from '#angular/core';
import { URLSearchParams, Jsonp, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
#Injectable()
export class BaseballService {
constructor(private jsonp: Jsonp) {}
search() {
return this.jsonp.request('http://api.sportradar.us/mlb-t6/players/6e1cac5c-b059-4b80-a267-5143b19efb27/profile.json?api_key=[hidden]')
.subscribe((data) => {
(data)
})}
}
which is called from here:
import { Component } from '#angular/core';
import { BaseballService } from './baseball.service'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [BaseballService]
})
export class AppComponent {
title = 'Baseball App';
constructor(private _baseballService: BaseballService) {
}
ngOnInit(){
let zx = this._baseballService.search();
console.log(zx);
}
}
I can't read the JSON data and am getting this error: JSONP injected script did not invoke callback.
I have tried a HTTP request but got nowhere. I tried following this example: http://plnkr.co/edit/8ap1Lm?p=preview

try this with http object
import { Injectable } from '#angular/core';
import { URLSearchParams, Jsonp, Http, Headers } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
#Injectable()
export class BaseballService {
headers: Headers;
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('content-type', 'application/json');
}
search() {
return this.http.get('http://api.sportradar.us/mlb-t6/players/6e1cac5c-b059-4b80-a267-5143b19efb27/profile.json?api_key=[hidden]',this.headers).map(resp => resp.json())
}
and in the component
import { Component, OnInit } from '#angular/core';
import { BaseballService } from './baseball.service'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [BaseballService]
})
export class AppComponent implements OnInit {
title = 'Baseball App';
zx: any;
constructor(private baseballService: BaseballService) {
}
ngOnInit(){
this.baseballService.search().subscribe((data) => {
this.zx = data;
console.log(this.zx);
});
}
}

Related

ERROR TypeError: _co.getAdmin is not a function

This is an Angular application and it's something wrong with function getAdmin() in auth.service, but I have no idea what. When I moved this function to app.component.ts and changed to "getAdmin()" in HTML, it was OK, but I need this function in service. Please tell me what's wrong and how can I fix it.
PS. variable admin returns 'true' or 'false' as a string.
It's e-Commerce app with user authentication, token and now I try to add admin.
auth.service.ts:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient, private _router: Router) { }
getAdmin() {
if (localStorage.getItem('admin') === 'true') return true;
return false;
}
}
app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _authService: AuthService) {
}
}
app.component.html:
<a class="nav-link" *ngIf="_authService.getAdmin()" routerLink="/admin" routerLinkActive="active">Admin</a>
It's always better to not call a function written in service from html . I think, you can resolve your current issue by changing your service scope from private to public. But the best way is to call a function inside component from html and call the getAdmin() inside service from that function. The best practise is to keep the service scope to private itself while doing dependency injection.
app.component.html
<a class="nav-link" *ngIf="adminExists()" routerLink="/admin" routerLinkActive="active">Admin</a>
app.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient, private _router: Router) { }
getAdmin() {
if (localStorage.getItem('admin') === 'true') return true;
return false;
}
}
app.component.ts
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _authService: AuthService) {
}
adminExists(){
return _authService.getAdmin();
}
}
Change scope of service private to public in app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public _authService: AuthService) {
}
}

Display data from json array using angular4

I am new to angular so please help me. I have an api returning an array of objects containing name, place id.
I need to display this in different cards on my html page, the cards being a widget.
in the parent component under the ngOnInit() section how do I access this json data and loop through the array in order to display it on my page as different cards?
Thank you in advance.
import { Component, OnInit } from '#angular/core';
import {HttpClient} from '#angular/common/http';
import { Observable } from 'rxjs/observable';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
showSplash = true
//public events: any = [];
events = [];
constructor(private http : HttpClient) { }
ngOnInit() {
this.showSplash = true
this.http.get("/events").subscribe(data => {
console.log("EVENTS ARE: ", data);
this.events = data;
console.log(this.events)
})
}
ngAfterViewInit(){
setTimeout(() => {
this.showSplash = false
}, 3000);
}
}
This will get you the events you want.
import { Component, OnInit, OnDestroy } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit, OnDestroy {
showSplash = true
events = [];
subscription: Subscription;
constructor(private http: HttpClient) {}
ngOnInit() {
this.subscription = this.http.get("/events").subscribe(data => {
this.events = data;
this.showSplash = false;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
You will have to implement a Child Component(EventComponent probably with the selector app-event) that will accept an event object as an #Input property. Then in your HomePageComponent Template, you can loop through the events like this:
<div *ngFor="let event of events">
<app-event [event]="event"></app-event>
</div>
Alternatively:
You can use the async pipe in your HomePageComponent's Template to avoid manually unsubscribing from the Observable Subscription. Your HomePageComponent Class code will change to:
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
events$;
constructor(private http: HttpClient) {}
ngOnInit() {
this.events$ = this.http.get("/events");
}
}
And then in HomePageComponent's Template:
<div *ngFor="let event of events$ | async">
<app-event [event]="event"></app-event>
</div>
Here's how your EventComponent would look like in this case:
import { Component, Input, OnChanges } from '#angular/core';
#Component({
selector: 'app-event',
templateUrl: './event.component.html',
styleUrls: ['./event.component.css']
})
export class EventComponent implements OnChanges{
#Input() event;
ngOnChanges() {
this.events$ = this.http.get("/events");
}
}

retrieve the method from auth.services.ts to login.component.ts in json

app/auth/auth.services.ts:
import {Injectable} from '#angular/core';
import {Router} from '#angular/router';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {User} from './user';
import {Http, Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class AuthService {
result: any;
constructor(private router: Router, private _http: Http) {}
getUsers() {
return this._http.get('/api/users').map(result => this.result = result.json().data);
}
}
http://localhost:3000/api/users :
{"status":200,"data":[{"_id":"5a63f4da17fc7e9e5548da70","name":"Jonson Doeal"},{"_id":"5a63faf417fc7e9e5548da71","name":"Jonson Bol"},{"_id":"5a64f44de87b3e2f80437c6b","name":"aaaa"}],"message":null}
I would like to retrieve data in json from the getUsers method so that I cancompare values
for () {
if (json_value_name == this.temp) {
}
}
login.component.ts:
import {AuthService} from './../auth/auth.service';
import {Component, OnInit} from '#angular/core';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(
private authService: AuthService
) {}
ngOnInit() {
}
onSubmit() {
this.authService.getUsers();
console.log('this.authService.getUsers() ' + JSON.stringify(this.authService.getUsers()));
}
}
the console returns:
this.authService.getUsers(){"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
I would like it to return in this form:
{"status":200,"data":[{"_id":"5a63f4da17fc7e9e5548da70","name":"Jonson Doeal"},{"_id":"5a63faf417fc7e9e5548da71","name":"Jonson Bol"},{"_id":"5a64f44de87b3e2f80437c6b","name":"aaaa"}],"message":null}
you need to use subscribe
onSubmit() {
this.authService.getUsers().subscribe(data => {console.log(JSON.stringify(data)});
}
Your best bet would something like this:
private myData: any[];
ngOnInit() {
myData = this.authService.getUsers();
}
onSubmit() {
console.log('this.authService.getUsers() ' + JSON.stringify(myData));
}
What you are receiving is the expected result from that method call. The http calls in angular return observables. That means you need to subscribe to what you are returning. Depending on what you are trying to do you may want to restructure your service or component to fully utilize the pattern.
In order to print your data try this in your component:
onSubmit() {
this.authService.getUsers().subscribe((data) => {
console.log(`users ${data}`)
});
}
Hopefully this can get you started on using observables.

Console.log to html element - Angular 4

Simple question. I have the following response from web service and I am observing it on chrome console. How do I deploy this onto Html element in angular 4? I tried to convert into JSON, but I encountered with another problem so I just decided to go with what I received after parseString.
All I want to do is, to display those fields in html element using Angular. For now, I just have component.ts file and trying to do something in html but can't figure out.
import { HttpClient, HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Observable';
import { RequestOptions, Response } from '#angular/http';
import { Injectable } from '#angular/core';
import { parseString } from 'xml2js'
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
//import { IMovie } from './movie';
#Injectable()
export class AppService {
private urlNorth = 'service';
constructor(private http: HttpClient) { }
getMovies(): Observable<any[]> {
const headers = new HttpHeaders();
headers.set('Content-Type', 'text/sml');
headers.set('Accept', 'text/xml');
headers.set('Content-Type', 'text/xml');
return this.http.get<any[]>(this.urlNorth, { headers })
.map(res => {
var result = res.text().replace('<string xmlns="service">', '').replace('</string>', '').replace(/</g, '<').replace(/>/g, '>');
parseString(result, (err, resultN) => {
if (err) {
return console.dir('invalid XML');
}
else {
console.log(resultN);
}
})
})
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Log data
This code:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Does not belong in your service file. This is a component decorator and it should be on your component. Like this:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _appService: AppService) { }
getProduction() {
this._appService.getProduction()
}
}
Then your index.html file should use the tag to display the HTML.
In looking at your code more closely, there are other issues as well. For example, you are calling getProduction two times. You should not be calling it from the service constructor.
Also, the subscribe should be in the component, not the service.
And you should be using Http OR HttpClient, not both.
And TestBed is only for use in tests ... not in services.
I have a more complete example of a working component/service here: https://github.com/DeborahK/Angular-GettingStarted in the APM-Final folder. Consider looking through that code (or starting with that code) and making adjustments as needed for your application.
Here is a working service. (Without a plunker I can't successfully show this with your code. So you will need to make the appropriate replacements for your example.)
Service
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { IMovie } from './movie';
#Injectable()
export class MovieService {
private moviesUrl = './api/movies/movies.json';
constructor(private http: HttpClient) { }
getMovies(): Observable<IMovie[]> {
return this.http.get<IMovie[]>(this.moviesUrl)
.do(data => console.log(JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Component:
import { Component, OnInit } from '#angular/core';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
#Component({
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {
movies: IMovie[];
errorMessage: string;
constructor(private movieService: MovieService) { }
ngOnInit(): void { this.getMovies(); }
getMovies(): void {
this.movieService.getMovies()
.subscribe(
(movies: IMovie[]) => this.movies = movies,
(error: any) => this.errorMessage = <any>error);
}
}

Angularjs 4 HTTP Get request to json file

I have the folowing problem, i cant load the data from json.
What I'm trying to do is access the given file address and spell the data but something does not load I tried and without async
driver-list.service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
#Injectable()
export class DriversListService {
private baseUrl: string = 'http://ergast.com/api/f1/2016/driverStandings.json';
constructor(private http : Http){}
data
getDriver() {
return this.http.get(this.baseUrl)
.map(res => this.data = res.json())
}
}
drivers-list-page.component.ts
import { Component, OnInit } from '#angular/core';
import { DriversListService } from '../drivers-list-page/drivers-list.service'
#Component({
selector: 'app-drivers-list-page',
templateUrl: './drivers-list-page.component.html',
styleUrls: ['./drivers-list-page.component.sass']
})
export class DriversListPageComponent implements OnInit {
drivers = []
constructor(private driverListServices: DriversListService) {}
ngOnInit(){
this.driverListServices.getDriver().subscribe(resDriverData=>this.drivers=resDriverData)
}
}
drivers-list-page.component.html
WORK
<ul class="items">
<li *ngFor="let driver of drivers | async">
<span>{{driver}}</span>
</li>
</ul>
enter image description here
Check the console log, to know more about the error...
then we can help you exactly
or try ...
import { Component, OnInit, Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-searcher',
templateUrl: './searcher.component.html',
styleUrls: ['./searcher.component.css']
})
#Injectable()
export class SearcherComponent implements OnInit {
// Pixabay API Key
private key:string = environment.PIXABAY_API_Key;
// API Url
url:string;
// Array of result
images:any[];
// Result per page
per_page:number;
// User query
query:string;
constructor(private result: Http) {
}
ngOnInit() {
}
// Get http result
letSearch(query){
this.url = "https://pixabay.com/api/?key=" + this.key + "&q=" + query;
return this.result.get(this.url).map(res => res.json()).subscribe(
data => console.log(data),
error => console.log(error),
() => console.log("Fine !")
);
}
}