Getting empty json data - javascript

I'm trying to get json data from the url, but i'm not able to get any.
It is just showing an empty array. What do you think that I'm missing
here?
service.ts
this is the service.ts. Im trying to get data from 'https://jsonplaceholder.typicode.com/posts'.
import { Injectable } from '#angular/core';
import{UserCreation} from '../../models/user-creation.model';
import{Observable} from 'rxjs/Observable';
import{of} from 'rxjs/observable/of';
import{catchError,map,tap} from 'rxjs/operators';
import{HttpClient,HttpHeaders} from '#angular/common/http';
const httpOptions={
headers:new HttpHeaders({'Content-Type':'application/json'})
};
#Injectable({
providedIn: 'root'
})
export class UserCreationService{
//Create constructor to get Http instance
constructor(private http:HttpClient) { }
private usersUrl:'https://jsonplaceholder.typicode.com/posts';
getUsers():Observable<UserCreation[]>{
return this.http.get<UserCreation[]>(this.usersUrl).pipe(
tap(receivedUsers
=>console.log(`receivedUsers=${JSON.stringify(receivedUsers)}`)),
catchError(error=>of([]))
);
}
app.component.ts
this is the component.ts file
import { Component, OnInit } from '#angular/core';
import { Http, Response } from '#angular/http';
import { UserCreationService } from '../../common/services/user-
creation.service';
#Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app-component.css']
})
export class AppComponent implements OnInit {
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();
}

There is typo error here - private usersUrl:'https://jsonplaceholder.typicode.com/posts';.
It should be = instead of : like this - private usersUrl='https://jsonplaceholder.typicode.com/posts';.
Or better way private usersUrl:string = 'https://jsonplaceholder.typicode.com/posts';

Related

How do I push data from a Subject observable to an array in the component?

I am trying to push a message into an array that is already declared as a variable in the component. I am using a service and have created a subject observable to take data from one component and inject it into another component. When I try to push the data onto the array after subscribing to the variable, it's updated temporarily but when I open that component, the data is not pushed. The array updates when I console log from inside the subscribe method but it's reset once I open that component. I don't know what is the problem. This is the code:
Service.ts
import { Injectable } from '#angular/core';
import { User } from './user';
import { Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SerService {
private message = new Subject<string>();
sourceMessage$ = this.message.asObservable();
constructor() { }
sendMessage(message: string) {
this.message.next(message);
}
}
Receiver component
import { Component, OnInit } from '#angular/core';
import { SerService } from '../ser.service';
import { User } from "../user";
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public messages = ['hi', 'hello', 'bye'];
constructor(private _service: Service) { }
ngOnInit() {
this._service.message$
.subscribe(
message => {
this.messages.push(message);
}
);
}
}
Sender Component
import { Component, OnInit } from '#angular/core';
import { SerService } from '../ser.service';
import { User } from '../user';
#Component({
selector: 'app-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent {
userModel = new User('', '', '', '', false);
constructor (private _service : SerService) {}
onSubmit(){
this._service.sendMessage(this.userModel.message);
}
}
I can't update the message array. How do I do this with minimal changes?
You can create a service to send data from one component to another by using BehaviourSubject
Service:
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable({
providedIn: 'root'
})
export class DataService {
private userDetails = new BehaviorSubject<any>('');
currentUserDetails = this.userDetails.asObservable();
constructor() { }
sendUserDetails(message){
this.userDetails.next(message)
}
}
Sender Component:
import { DataService } from '/services/data.service';
export class SignupComponent implements OnInit {
public userDetails;
constructor(private _dataService: DataService) {}
ngOnInit(){
userDetails = new User('', '', '', '', false);
this._dataService.sendUserDetails(this.userDetails);
}
}
Receiver Component
import { DataService } from '/services/data.service';
export class LoginComponent implements OnInit {
public userDetails;
constructor(private _dataService: DataService) {}
ngOnInit(): void {
this._dataService.currentUserDetails.subscribe(userDetails => this.userDetails = userDetails);
}
Blockquote

How to import a page property to a data service with Angular?

I want to import the trackingId from tracking.page.ts to geolocation.service.ts in my Ionic App. Anyone an idea how to do that with Angular and TypeScript?
Below you can see an extract of the code.
tracking.page.ts
import { Component, OnInit, ViewChild, ElementRef } from '#angular/core';
import { Geolocation } from '#ionic-native/geolocation/ngx';
import { GeolocationService } from '../../app/geolocation.service';
import { UserService } from '../../app/user.service';
import { Insomnia } from '#ionic-native/insomnia/ngx';
import { LoadingController } from '#ionic/angular';
import { AlertController } from '#ionic/angular';
import { AppComponent } from '../app.component';
import { Storage } from '#ionic/storage';
declare var google;
#Component({
selector: 'app-tracking',
templateUrl: './tracking.page.html',
styleUrls: ['./tracking.page.scss'],
})
export class TrackingPage implements OnInit {
#ViewChild('map', { static: true }) mapElement: ElementRef;
map: any;
markers = [];
geoLocations: any;
watchLocationUpdates: any;
isWatching: boolean;
interval: any;
geoLatitude: number;
geoLongitude: number;
geoAccuracy: number;
timeStamp: any;
uId: string;
trackingId: string; // This is the trackingId
...
geolocation.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class GeolocationService {
databaseUrl = environment.firebase.databaseURL;
constructor(private http: HttpClient
) {
console.log('Hello GeolocationService Provider');
console.log('GeolocationService: ', this.databaseUrl);
}
...
You can make a service to save the trackingid inside it and then inject it inside the second page.
Trying to do this outside of services will run into problems with Zoning and change detection.
Define trackingid in service file with observable subject like
public trackingid: BehaviorSubject<number> = new BehaviorSubject(1);
And then set it inside service and fetch it also like below
public getTrackingId(): boolean {
return this.trackingid.value;
}
public setTrackingId(){
return this.trackingid.next(2);
}
Now from component you can do get and set to trackingId.

Angular 5 - HttpClient Service - Component not getting data

I am using Angular 5 and trying to get some data from JsonPlaceholder.
First I created the service, then added:
import { HttpClientModule } from '#angular/common/http';
This is the service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'http://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
this.http.get(`${this.ROOT_URL}/posts`).subscribe(data => {
return data;
});
}
}
And finally, on my app.component.ts:
import { Component, OnInit } from '#angular/core';
import { DataService } from '../../services/data.service';
#Component({
selector: 'app-root',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {
data;
constructor(private dataService: DataService) {
this.data = dataService.getPosts();
console.log(this.data;
}
ngOnInit() {
}
}
On the console it's just returning 'Undefined'
What I'm I doing wrong?
Don't subscribe on the service, return the observable and subscribe to it on the component. Because it is asynchronous your data variable on the component will be undefined because you assigned before the http request could resolve a value.
On the service:
getPosts() {
return this.http.get(`${this.ROOT_URL}/posts`);
}
On the coponent:
ngOnInit() {
this.dataService.getPosts().subscribe(posts => this.posts = posts);
}
Try following code snippet.
You are getting undefined because you assigning the data before the http request could resolve a value. Remove the subscription from service and move it to component.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get(`${this.ROOT_URL}/posts`);
}
}
AppComponent.ts
import { Component } from '#angular/core';
import {DataService} from './data.service';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor(public data:DataService){
this.data.getPosts().subscribe(data=>{
console.log(data);
})
}
}
See the Demo here
import { HttpClientModule } from '#angular/common/http';
//This is the service code:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable()
export class DataService {
private ROOT_URL = 'http://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
//if you want to use the observable which returns from .get()
//.. you need to do "return"
return this.http.get(`${this.ROOT_URL}/posts`);
}
}
//app.component.ts:
import { Component, OnInit } from '#angular/core';
import { DataService } from '../../services/data.service';
#Component({
selector: 'app-root',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {
data;
constructor(private dataService: DataService) {
this.data = dataService.getPosts();
//so if you want to use the value of your http call outside..
//..of the service here is a good place where to do subscribe()
this.data.subscribe(data => {
console.log(this.data;
});
}
ngOnInit() {
}
}
You expect a return value and returns nothing. Your return statement is placed inside a nested-lambda function, thus using "return" in the place you used it causes the inner function to return a value, and not the outer one as you needed.
I suggest you to read about asynchronous programming, and particularly about Observable (which works on the same concept of Promise) in Angular.
I basically agree to #Eduardo Vargas answer, but it might be also a good idea to do it in resolver, which will call api, and put data into route snapshot. Thanks to this it won't wait on empty page for loading the data on subscribe in constructor. More info here:
https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

Http call as service in Angular

I am brand new to Angular and I am attempting to make a simple http request for data. How do I access this data in my component? I am getting the error 'Cannot read property 'get' of undefined'
data.service.ts
import { Injectable } from '#angular/core'
import { HttpClient } from '#angular/common/http'
#Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).subscribe(data => {
console.log(data)
})
}
}
table.component.ts
import { FetchData } from './datatable.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
Data: FetchData
constructor() { }
ngOnInit() {
this.Data.get()
}
}
You need to "Inject" the service in your component and also make the subscription in your component.
In your service you should "map" your response.
import { Injectable } from '#angular/core'
import { HttpClient } from '#angular/common/http'
import 'rxjs/add/operator/map';
#Injectable()
export class FetchData {
private url: string = 'https://jsonplaceholder.typicode.com/users'
constructor(private http: HttpClient){}
get(){
return this.http.get(this.url).map(data => {
return data.json();
})
}
}
Your component:
import { FetchData } from './datatable.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {
constructor(private fetchDataService: FetchData) { }
ngOnInit() {
this.fetchDataService.get().subscribe(res => {
console.log(response);
});
}
}
try this:
export class DatatableComponent implements OnInit {
constructor(private dataService: FetchData) { }
ngOnInit() {
this.dataService.get()
}}

Angular Firebase Database Querying

This is my .ts file
import { Component, OnInit } from '#angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
#Component({
selector: 'app-candidate-reg-success',
templateUrl: './candidate-reg-success.component.html',
styleUrls: ['./candidate-reg-success.component.css']
})
export class CandidateRegSuccessComponent implements OnInit {
constructor() {
debugger;
const rootRef=firebase.database.ref();
const mail=rootRef.child('candidates_list').orderByChild('email').equalTo('pranavkeke#gmail.com');
console.log(mail);
}
ngOnInit() {
}
}
I am trying to query the user from candidates_list table which has the email address pranavkeke#gmail.com.
But I am unable to console it. It shows a error like
Property 'ref' does not exist on type 'typeof database'.
Any solution to query angular firebase database?
you need to inject the AngularFirebaseData in constructor and change the code and try again
import { Component, OnInit } from '#angular/core';
import { AngularFireDatabase, FirebaseListObservable,
FirebaseObjectObservable } from 'angularfire2/database';
#Component({
selector: 'app-candidate-reg-success',
templateUrl: './candidate-reg-success.component.html',
styleUrls: ['./candidate-reg-success.component.css']
})
export class CandidateRegSuccessComponent implements OnInit {
constructor(public db: AngularFireDatabase) {
debugger;
db.list('/candidates_list', ref => ref.orderByChild('email').equalTo('pranavkeke#gmail.com'));
}
ngOnInit() {
}}

Categories