Angularjs 4 HTTP Get request to json file - angularjs-http

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 !")
);
}
}

Related

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

Angular 2/4 can't get json response to show in html component

So I'm trying to return my JSON response into the html component and I have no luck after trying for hours and numerous google/stackoverflow searches. When I use console.log the results show, when I try to show the results in the html component I get nothing. But when I return the results inside an alert i get [object, object]. Can anyone help?
BTW im trying to include the result in *ngif and as text.
data.service.ts file
import { Injectable } from '#angular/core';
import { Http, Response, HttpModule, RequestOptions, Headers } from
'#angular/http';
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { FormGroup, FormControl } from '#angular/forms';
import { BrowserModule } from '#angular/platform-browser';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class DataService {
constructor(public http_: HttpClient) { }
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_)
.subscribe(
res => {
console.log(res[a]);
var data = res[a];
}
);
}
}
account.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl } from '#angular/forms';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { JsonPipe } from '#angular/common';
import { DataService } from '../data/data.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
declare var $: any;
#Component({
selector: 'app-account',
templateUrl: './account.component.html',
providers: [DataService]
})
export class AccountComponent implements OnInit {
public currentType:string;
constructor(private dataService: DataService, private http_: HttpClient) { }
ngOnInit() {
alert(this.dataService.userInfo_('type'));
}
var currentType = this.dataService.userInfo_('type');
}
account.component.html
<div> {{ currentType }}</div>
<div *ngIf="currentType == 'User'">I'm a user</div>
JSON response
{"type":"User"}
Sorry if the code is a bit messy, i've tried a lot of things out.
Your userInfo is not returning a thing it should be
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_).subscribe(res => res[a]);
}
and your this.currentType variable should be inside some method e.g. ngOnInit
Personally I do this stuff like this:
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_);
}
and than
ngOnInit() {
this.dataService.userInfo_('type').subscribe(res=>{
this.currentType = res['type'];
})}
Your service should return an observable, change it as
#Injectable()
export class DataService {
constructor(public http_: HttpClient) { }
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_);
}
}
you should use this instead of var and place it inside ngOnInit()
export class AccountComponent implements OnInit {
public currentType:string;
constructor(private dataService: DataService, private http_: HttpClient) { }
ngOnInit() {
this.dataService.userInfo_('type').subscribe(res=>
this.currentType = res.type;
)}
}
}

Unable to read JSON returned from API trying Angular2

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

angular2 rxjs .map does't work in version 2.0.1

This code works on angular2 v.2.0.0 .rc.2 but does't on angular2 v2.0.1
app.appcomponent.ts
import { Component, OnInit } from "#angular/core";
import { Injectable } from '#angular/core';
import { Http, Response, URLSearchParams } from "#angular/http";
import { IFood } from "./food";
import { Headers, RequestOptions } from "#angular/http";
I can import this for use .map right?
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
#Component({
selector: "my-app",
template: `
<h1>My First Angular 2 App</h1>
<ul *ngFor='let food of foods'>
<li>{{food.foodName}}</li>
</ul>
`,
templateUrl: "./app/form.html"
})
#Injectable()
export class AppComponent implements OnInit {
public values: string[];
public headers: Headers;
errorMessage: string;
I have a list of food in my controller, foodid, foodname
foods: IFood[];
foodModel = <IFood>{};
constructor(private http: Http) {
this.http = http;
this.headers = new Headers();
this.headers.append("Content-Type", "application/json");
}
ngOnInit() {
return this.http.get("/home/getdata")
there's .map does't work, can't we use .map in angular2 2.0.1?
.map((response: Response) => <IFood[]>response.json())
.subscribe(data => this.foods = data, error =>
this.errorMessage = <any>error);
}
}
Do I need to create Services?
How to fix this, thank you
Try updating to Typescript 2.0.3
This solved the issue for me.
And make sure you are using ECMAScript 6