How to take the data from the angular2 firebase data.? - javascript

I have candidates_list table in angular2 firebase, but I am not getting the value from it.
My ts file is this
import { Component, OnInit,Input } from '#angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import * as firebase from 'firebase';
import { FirebseService } from "app/firebse.service";
#Component({
selector: 'app-candidate-reg-complete',
templateUrl: './candidate-reg-complete.component.html',
styleUrls: ['./candidate-reg-complete.component.css']
})
export class CandidateRegCompleteComponent implements OnInit {
content:any;
item: FirebaseObjectObservable<any>;
constructor(private db: AngularFireDatabase,
private firebaseService:FirebseService) {
this.item = db.object('candidates_list');
}
ngOnInit() {
}
upload(documents){
// let file=user.files[0];
// console.log(file);
// console.log(file.name);
let storageRef=firebase.storage().ref();
for(let selectedFile of[(<HTMLInputElement>document.getElementById('file')).files[0]]){
let path='/resumes/'+selectedFile.name;
let iRef=storageRef.child(path);
iRef.put(selectedFile).then((snapshot)=>{
debugger;
documents.resume=selectedFile.name;
documents.path=path;
var Userid=localStorage.getItem('user');
console.log(documents);
let content=this.db.object('/candidates_list/'+Userid);
console.log(content);
// this.db.object('/candidates_list/'+Userid).update(documents);
localStorage.setItem('resume',documents.path);
})
}
}
}
The problem is with this code
let content=this.db.object('/candidates_list/'+Userid);
console.log(content);
When I try to console this value, the output is like this..
FirebaseObjectObservable {_isScalar: false, $ref: U, source: FirebaseObjectObservable, operator: ObserveOnOperator}
Not conoling the exact content, so any solution for this problem?

You need to subscribe to the observable. Try this:
let content = this.db.object('/candidates_list/'+Userid)
content.subscribe(data => {
console.log(data)})

Related

How to extract values from BehaviouralSubject in Angular

I created an Account Service, for my angular application, and it handles the Login and logout. and this works perfectly. But I am having an issue, I used BehaviourSubject Observables to render the variables.
I am trying to retrieve the loginstatus value, and the username string on the component using the service, but the observable is returning an object, and I am having problems extracting the string out of the object. How can I extract variable types from Behavioursubject observables?
The Account Service...
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AccountService {
private baseUrlLogin:string = "/api/account/login";
private loginStatus = new BehaviorSubject<boolean>
(this.checkLoginStatus());
private userName = new BehaviorSubject<string> localStorage.getItem['username']);
constructor(
private http:HttpClient,
private router: Router
){}
login(username:string, password:string){
return this.http.post<any>(this.baseUrlLogin,{username, password}).pipe(
map(result => {
if(result && result.token){
localStorage.setItem('loginStatus', '1');
localStorage.setItem('username', result.username),
}
return result;
})
);
}
logout(){
this.loginStatus.next(false);
localStorage.setItem('loginStatus', '0');
localStorage.removeItem('username'),
localStorage.clear();
//now redirect to the login page...
this.router.navigate(['/login']);
console.log("logged out successfully...");
}
get isLoggedIn(){
return this.loginStatus.asObservable();
}
get currentUserName(){
return this.userName.asObservable();
}
}
The Component Using the Service
import { Component, Input, OnInit } from '#angular/core';
import { AccountService } from 'src/app/services/account.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
pgtitle:string = "SCB Dashboard";
loginStatus$ : Observable<boolean>;
username$ : Observable<string>;
constructor(
private acc:AccountService
){}
ngOnInit() {
this.loginStatus$ = this.acc.isLoggedIn;
this.username$ = this.acc.currentUserName;
console.log(this.loginStatus$); //here it ruturns an object
console.log(this.username$); //and here too...
}
}
The console.log() returns an object, but how do I retrieve the variables, and work with them in the controller, since they are of type observable?
Rxjs BehaviourSubject has an asObservable() method, you can generate your observable from it
let sourceSubject = new BehaviourSubject();
let source$ = sourceSubject.asObservable();
source$.subscribe(result => // Your data)
// Update the BehaviourSubject
sourceSubject.next(newValue);
You need to subscribe to the observable to get the value out of it:
this.loginStatus$.subscribe(value => {
console.log(value); // access value
});
try this:
get isLoggedIn(){
return this.loginStatus.value;
}
get currentUserName(){
return this.userName.value;
}
This should also work:
ngOnInit() {
this.loginStatus$ = this.acc.isLoggedIn.pipe(
tap(status => console.log(status))
);
this.username$ = this.acc.currentUserName.pipe(
tap(userName => console.log(userName))
);
}
Assuming that you subscribed somewhere, such as with an async pipe.

Angular 5 - HTTP Client - converting resp.body to Array

I am trying to get my JSON response from the HttpClient service into an array so that I can loop through using *ngFor in my html. I've tried using "this" to loop through but *ngFor will not accept it. Below is the code for my service.ts component and the main component.ts.
I just need some way to convert an array from "resp.body" into an exportable Array to be used for string interpolation in the html. Any help would be much appreciated!
races.component.ts
import { Component, OnInit } from '#angular/core';
import {Race, RacesService} from './races.service';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'dh-races',
templateUrl: './races.component.html',
providers: [ RacesService ],
styleUrls: ['./races.component.scss']
})
export class RacesComponent {
error: any;
headers: string[];
race: Race;
raceM: any[];
constructor(private racesService: RacesService) {
var raceM = [];
var raceArray = [];
this.racesService.getRaceResponse()
.subscribe(resp => {
raceArray.push(resp.body);
for (let obj of raceArray) {
for (let i in obj) {
raceM.push({
"ID": obj[i].id + ",",
"Date": obj[i].activityStartDate,
"RaceName": obj[i].assetName,
"Website": obj[i].website
})
}
console.log(raceM);
return raceM;
}
});
}
races.service.ts
#Injectable()
export class RacesService {
constructor(private httpClient: HttpClient) { }
getRace() {
return this.httpClient.get(activeApiURL).pipe(
retry(3),
catchError(this.handleError)
);
}
getRaceResponse(): Observable<HttpResponse<Race>> {
return this.httpClient.get<Race>(
activeApiURL, {
observe: 'response'
});
}
To fix the issue, you need to create an interface that matches the data you get from the server, I will call this interface IRace.
Then in the component I will create a variable named races, I will assign the returned value from the server response i.e. resp.body to the races variable.
I'd change the service to look like this:
export interface IRace {
// Your response from server object's properties here like so:
id: Number;
assetName: string;
...
}
export class RacesService {
constructor(private httpClient: HttpClient) { }
getRace() {
return this.httpClient.get(activeApiURL).pipe(
retry(3),
catchError(this.handleError)
);
}
getRaceResponse(): Observable<HttpResponse<Array<Race>>> {
return this.httpClient.get<Array<Race>>(
activeApiURL, {
observe: 'response'
});
}
}
Finally, I'd change the race component to this:
import { Component, OnInit } from '#angular/core';
import { Race, RacesService, IRace } from './races.service';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'dh-races',
templateUrl: './races.component.html',
providers: [ RacesService ],
styleUrls: ['./races.component.scss']
})
export class RacesComponent {
error: any;
headers: string[];
races: IRace[];
constructor(private racesService: RacesService) {
this.racesService.getRaceResponse()
.subscribe(resp => {
this.races = resp.body;
});
}
}
I hope this helps.

How to use http subscribe with rxjs map to fetch two arrays of objects

I've the following arrays of objects returned from the backend:
Array(object1):
[{"record_id":"1", "local_TimeStamp":"16:00:00", "country":"USA"},
{"record_id":"2", "local_TimeStamp":"17:00:00", "country":"Japan"},
{"record_id":"3", "local_TimeStamp":"17:00:00", "country":"Korea"},
{"record_id":"4", "local_TimeStamp":"15:00:00", "country":"Thailand"},
{"record_id":"5", "local_TimeStamp":"16:00:00", "country":"China"}]
Array(object2):
[{"record_id":"100", "Brand_Name":"Swire", "Shippment-type":"Air"},
{"record_id":"101", "Brand_Name":"Toshiba", "Shippment-type":"Ground"},
{"record_id":"102", "Brand_Name":"RiUP", "Shippment-type":"Special"},
{"record_id":"103", "Brand_Name":"Lenovo", "Shippment-type":"Local"},
{"record_id":"104", "Brand_Name":"TopCon", "Shippment-type":"Ground"}]
I tried to fetch these two http returned arrays into two local arrays but fail. Here is my code:
shippmentProvider ts file:
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) {};
getBackEndService()
{return this.http.get("http://local:8080/shippment.dat/")}
//
view ts file:
this.shippmentProvider.getBackEndService().map((data: any[]) =>
{ let localArray: any[] = data[0];
let localArray1: any[] = data[1];
})
.subscribe(localArray => console.log(localArray))
.subscribe(localArray1 => console.log(localArray1));
Error: {error: SyntaxError: Unexpected token [ in JSON at position 6 at JSON.parse....}
It seems that the above code couldn't fetch the second array objects. Please help !
Amendment:
With the advice from Fateh Mohamed, I'd modified the code as follow; however, the console.log seems never executed. Any ideas?
view ts file:
import { Observable} from 'rxjs/Rx';
import { Subscription } from 'rxjs/Subscription';
subscription: Subscription;
localArray: Observable<Array<any>>;
localArray1: Observable<Array<any>>;
constructor(private http: HttpClient) {};
this.shippmentProvider.getBackEndService().map((data:Observable<Array<any>>) =>
{
this.localArray = data[0]; this.localArray1 = data[1];
const Obs = Observable.combineLatest(this.localArray, this.localArray1,
(array1, array2) => ({ array1, array2}));
this.subscription = Obs.subscribe((arrays) => {
console.log(arrays.array1);
console.log(arrays.array2);
});
No errors but no console.log response neither!
you can create 2 Observables for each result and use combineLatest, that way you can subscribe only once
const Obs = Observable.combineLatest(array1Observable, array2Observable,
(array1, array2) => ({ array1, array2}));
this.subscription = Obs.subscribe((arrays) => {
console.log(arrays.array1);
console.log(arrays.array2);
})
here is the final file
import { Component } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/combineLatest';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
subscription: Subscription;
array1Obs = Observable.of(
[{"record_id":"1", "local_TimeStamp":"16:00:00", "country":"USA"},
{"record_id":"2", "local_TimeStamp":"17:00:00", "country":"Japan"},
{"record_id":"3", "local_TimeStamp":"17:00:00", "country":"Korea"},
{"record_id":"4", "local_TimeStamp":"15:00:00", "country":"Thailand"},
{"record_id":"5", "local_TimeStamp":"16:00:00", "country":"China"}]);
array2Obs = Observable.of(
[{"record_id":"100", "Brand_Name":"Swire", "Shippment-type":"Air"},
{"record_id":"101", "Brand_Name":"Toshiba", "Shippment-type":"Ground"},
{"record_id":"102", "Brand_Name":"RiUP", "Shippment-
type":"Special"},
{"record_id":"103", "Brand_Name":"Lenovo", "Shippment-type":"Local"},
{"record_id":"104", "Brand_Name":"TopCon", "Shippment-type":"Ground"}]);
ngOnInit() {
const Obs = Observable.combineLatest(this.array1Obs, this.array2Obs,
(array1, array2) => ({ array1, array2}));
this.subscription = Obs.subscribe((arrays) => {
console.log(arrays.array1);
console.log(arrays.array2);
})
}
}

Angular Firebase Querying?

This is my .ts file to query the angular firebase database
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 {
result:any;
items: FirebaseListObservable<any[]>;
constructor(db: AngularFireDatabase) {
debugger;
this.items=db.list('/candidates_list',{
query:{
orderByChild:'email',
equalTo:'pranavkeke#gmail.com'
}
});
this.items.subscribe(quiredItems=>{
this.result=quiredItems;
console.log(this.result);
console.log(this.result.FirstName);
// console.log();
});
// debugger;
// const rootRef=firebase.database().ref();
// const mail=rootRef.child('candidates_list').orderByChild('email').equalTo('pranavkeke#gmail.com');
// console.log(mail);
}
ngOnInit() {
}
}
I am getting the user with specified criteria, but I want only the firstname of the user.The problem is with this one
console.log(this.result.FirstName);
The result variable holds all the json data from firebase, butI want only firstname. But in console it shows undefined. How can be it solved? Please help me. Thanks in advance.
try to transform each item in the FirebaseListObservable first:
this.items=db.list('/candidates_list',{
query:{
orderByChild:'email',
equalTo:'pranavkeke#gmail.com'
}})
.map(item => item.FirstName) as FirebaseListObservable<any[]>;

Firebase doesn't return value (Angular 2)

I try to retrieve data from my Firebase and it works, but JUST for console.log().
I can't return a value into a var...
As I'm working with Angular 2 & Typescript I have
a Service:
import {Injectable} from "angular2/core";
import 'rxjs/Rx';
import {Observable} from "rxjs/Observable";
declare var Firebase: any;
#Injectable()
export class DataService {
getAllData() {
const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
firebaseRef.on("value", function (snapshot) {
console.log(snapshot.val()); // THIS WORKS!
return snapshot.val(); // THIS DOES NOT WORK!
});
}
and a Component:
#Component({
templateUrl: 'templates/user.tpl.html',
providers: [DataService],
})
export class UserComponent implements OnInit{
userData: any;
constructor(private _dataService: DataService){}
ngOnInit():any {
this.userData = this._dataService.getAllData();
console.log(this.userData); // THIS DOES NOT WORK: UNDEFINED
}
If i run that, I get nothing for my userData var... And I can't figure how to fix that. I thought I would need an Observable but I failed, whatever I tried to do...
Can someone help?
You need to wrap your call into an observable since Firebase is event-driven:
getAllData() {
const firebaseRef = new Firebase('https://XYZ.firebaseio.com/path/user')
return Observable.create((observer) => {
firebaseRef.on("value", function (snapshot) {
console.log(snapshot.val());
observer.next(snapshot.val());
});
});
}
This way you will be able to receive value by subscribing on the returned observable:
ngOnInit():any {
this._dataService.getAllData().subscribe(data => {
this.userData = data;
});
}

Categories