retrieve the method from auth.services.ts to login.component.ts in json - 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.

Related

how can i fetch my local json file in angular 13.2 and display data with html

its literally my third day trying to do that.thats what i achieved ,it displays nothing
,what i really want to do is to fetch data from lacal json so that every json element will be displayed in a html block
Service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
this.getJSON().subscribe(matches => console.log(matches))};
public getJSON(): Observable<any> {
return this.http.get("./matches.json");
}
}
component.ts
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../api.service';
#Component({
selector: 'app-matches',
templateUrl: './matches.component.html',
styleUrls: ['./matches.component.css']
})
export class MatchesComponent implements OnInit {
constructor(private ApiService : ApiService) { }
ngOnInit(): void {
this.ApiService.getJSON().subscribe(data => {
console.log(data);
});
}
}
matches.json
[{"id":"1","homeTeam":"Es Tunis","awayTeam":"Tatawin","dateM":"2022-04-21","stade":"Rades","NBtickets":"20000"},
{"id":"2","homeTeam":"Rejiche","awayTeam":"Etoile du sahel","dateM":"2022-04-11","stade":"Mahdia","NBtickets":"15000"},
{"id":"3","homeTeam":"Cs Cheba","awayTeam":"Solimane","dateM":"2022-04-11","stade":"Cheba","NBtickets":"5000"},
{"id":"4","homeTeam":"Zarzis","awayTeam":"Club Africain","dateM":"2022-04-11","stade":"Jlidi","NBtickets":"10000"},
{"id":"5","homeTeam":"Olympique Beja","awayTeam":"Monastir","dateM":"2022-04-11","stade":"Boujemaa Kmiti","NBtickets":"15500"},
{"id":"6","homeTeam":"Ca Bizert","awayTeam":"Cs Sfaxien","dateM":"2022-04-11","stade":"Tayeb mhiri","NBtickets":"10000"},
{"id":"7","homeTeam":"Hammam-sousse","awayTeam":"Ben Gerdane","dateM":"2022-04-11","stade":"Bouaali hwar","NBtickets":"12000"},
{"id":"8","homeTeam":"hammam-Lif","awayTeam":"Metlaoui","dateM":"2022-04-11","stade":"Stade municipale","NBtickets":"10000"}]
why wont my code display anything?
ps:i tried many things such as importing file.json but nothing worked(im beginner)

Angular 6: use a service to get local json data

I have a movies.json that contain a list of movies and I want to create a MoviesServices to get the data where I want.
My MoviesServices:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { HttpErrorResponse } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class MoviesService {
movies: string[];
constructor(private httpService: HttpClient) {
this.getMovies();
}
getMovies() {
this.httpService.get('../../assets/movies.json').subscribe(
data => {
this.movies = data as string[];
console.log(this.movies); // My objects array
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
console.log(this.movies); // Undefined
}
}
Firstly, I have no idea why the first console.log() works and the second not, can you tell me why ?
Here is my component where I need to get the data:
import { Component, OnInit } from '#angular/core';
import { MoviesService } from '../services/movies/movies.service';
#Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
title = 'films-synopsys';
movies;
constructor(private myService: MoviesService) {}
ngOnInit() {
console.log(this.myService.movies); // Undefined
}
}
Of course this is not working. Can you tell me how must I do ? I'm newbie angular
So basically you need to return an Observable from your service and then subscribe to it from your Component. You can then assign your response to the Component property movies
Try this:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class MoviesService {
constructor(private httpService: HttpClient) { }
getMovies() {
return this.httpService.get('../../assets/movies.json');
}
}
And in your Component:
import { Component } from '#angular/core';
import { MoviesService } from './movies.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'films-synopsys';
movies;
constructor(private myService: MoviesService) {}
ngOnInit() {
this.myService.getMovies()
.subscribe(res => this.movies = res);
}
}
Here's a Sample StackBlitz for your ref.
Change your method to return an Observable which you can subscribe to:
import { Observable } from 'rxjs/Observable';
...
getMovies(): Observable<string []> {
this.httpService.get('../../assets/movies.json').subscribe(
data => {
this.movies = data as string[];
return this.movies;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
In your calling code:
import { Subscription } from 'rxjs/Subscription';
this.myService.getMovies().subscribe(movies => {
console.log(movies); // My objects array
}
The reason the first console log works is because you are doing it within an observable's subscription. Subscriptions have three states, Next, Error, Complete and so when you console log the first time, within the subscription next state you get the value that was pushed out from the event stream.
In your component the reason why it doesn't work is due to the fact that observables are lazy, and that you need to initialize the data by calling this.myService.getMovies() first to make the subscription happen.
A better way to do this would been to pass observables around and use async pipe in the html template.

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

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