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[]>;
Related
EDIT: I made changes in the push method but it still did not work
I am making get request to an api and pushing each of the responses to an array. The array is visible when logged to console. On printing the length of the array in the template length comes out to be 5. But when I try to iterate through it using ngFor no output is being displayed
Service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {Quote} from 'src/app/models/quote';
#Injectable({
providedIn: 'root'
})
export class StockpriceService {
url1='https://financialmodelingprep.com/api/v3/quote-short/';
url2='?apikey=efa24b272821b542c459557332c02a1e';
constructor(private http:HttpClient) {
}
//alpha apikey="VETRGM94G70WQGX9";
getQuote(symbol:string) //load data from api
{
return this.http.get<Quote>(this.url1 + symbol + this.url2);
}
}
ts file
import { Component, OnInit } from '#angular/core';
import{Quote} from 'src/app/models/quote';
import{StockpriceService} from 'src/app/services/stockprice.service';
import { timer } from 'rxjs';
#Component({
selector: 'app-stocks',
templateUrl: './stocks.component.html',
styleUrls: ['./stocks.component.css']
})
export class StocksComponent implements OnInit {
stocks: Array<Quote>=[];
symbols=['AAPL', 'GOOG', 'FB', 'AMZN', 'TWTR'];
constructor(private serv:StockpriceService) { }
ngOnInit(): void {
this.symbols.forEach(symbol => {
this.serv.getQuote(symbol).subscribe(
(data:Quote)=>{
console.log(data);
this.stocks.push(
{
symbol:data.symbol,
price:data.price,
volume:data.volume
}
);
}
)
});
console.log('stocks array is')
console.log(this.stocks);
}
}
Template
<div *ngFor="let stock of stocks">
{{stock.symbol}}
{{stock.price}}
</div>
sample api response
[ {
"symbol" : "AAPL",
"price" : 126.81380000,
"volume" : 36245456
} ]
Accordingly I have an interface defined for it as
export interface Quote{
symbol:string;
price:number;
volume:number;
}
This will work fine.
this.serv.getQuote(symbol).subscribe((data: Quote[]) => {
console.log(data);
this.stocks.push(...data);
});
There is a lot of documentation and examples of firestore collections getting realtime updates. However, there is very little for those who wish to have a single document have real time updates. I want to have a single document (an item), on a page where only the item will be viewed and manipulated and any changes to document, will have realtime updating.
Here is my component that wants to do stuff with the item:
import { Component, OnInit } from '#angular/core';
import { ItemsService } from '../shared/items.service';
import { ActivatedRoute, Router } from '#angular/router';
#Component({
selector: 'app-view-item',
templateUrl: './view-item.component.html',
styleUrls: ['./view-item.component.css']
})
export class ViewItem implements OnInit {
item;
private sub: any;
constructor(
// Service used for Firebase calls
private itemsService: ItemsService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
// Item retrieved from */item/:id url
this.sub = this.route.params.subscribe(params => {
this.getItem(params['id']);
});
}
getItem = (id) => {
this.itemsService.getItem(id).subscribe(res => {
console.log(res);
this.item = res;
console.log(this.item);
});
}
And the service it uses for calls:
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '#angular/fire/firestore';
#Injectable({
providedIn: 'root'
})
export class ItemsService {
constructor(
private firestore: AngularFirestore
)
getItem(id) {
return this.firestore.collection('items').doc(id).snapshotChanges();
}
}
The log I get for console.log(this.item) is undefined. Calling this.item in the console returns the same. I am unsure of how to proceed and would appreciate any guidance. Logging res in the console returns a byzantine object. Perhaps that's how I access the item, but if so, why is it not saved in this.item and how do I access the item's values?
snapshotChanges returns an observable of actions, not the actual value.
You should extract the value with action.payload.doc.data():
So your code should look like the following example.
getItem(id) {
return this.firestore.collection('items').doc(id).snapshotChanges()
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
})
);
}
Or you can use valueChanges of doc.
getItem(id) {
return this.firestore.collection('items').doc(id).valueChanges();
}
I'm getting the below error in my console when trying to run my Angular application. Here is my html code if you need it https://stackblitz.com/edit/angular-xrbrjq?file=src%2Fapp%2Fapp.component.html
Error: Can't resolve all parameters for HomeInnerComponent: (?).
Please have a look below for my component details.
Home-inner.component.ts:
import { Component, OnInit } from '#angular/core';
import {CategoriesService } from '../../Admin/categories/categories.service';
import {Categories } from '../../Admin/categories/categories';
#Component({
selector: 'app-home-inner',
templateUrl: './home-inner.component.html',
styleUrls: ['./home-inner.component.css']
})
export class HomeInnerComponent implements OnInit {
leftCat:Categories;
constructor(private leftCategoriesService: CategoriesService) { }
ngOnInit() {
// For showing category list in the left side
this.leftCategoriesService.getCategories()
.subscribe((data: any) => {
this.leftCat = data;
//console.log(this.leftCat);
// localStorage.removeItem('editEmpId');
});
// Left side category list ends here
}
}
In my Angular app I am trying to update records on Firebase database. I am using AngularFireDatabase to first bind the list when then be used to update the particular records. But the problem is that there is no $key.
The app.component.html code is:
<ul>
<li *ngFor="let course of courses">
{{course}}
<button (click)="update(course)">Update</button>
</li>
</ul>
The app.component.ts is:
import { AngularFireDatabase } from 'angularfire2/database';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {
courses: any[];
constructor(private db: AngularFireDatabase) {
this.subscription = db.list('/couses').valueChanges().subscribe(c => {
this.courses = c;
});
}
update(course) {
console.log(course.$key);
//gives key undefined
}
}
How to get key so that I can update a particular record?
The snapshot of firebase database is:
I solved the problem using .snapshotChanges() method.
The constructor code becomes:
constructor(private db: AngularFireDatabase) {
this.subscription = db.list('/couses').snapshotChanges().subscribe(c => {
this.courses = c;
});
The update() method:
update(course) {
this.db.list('/couses').set(course.key,"Updated");
}
So Now I am getting the key for doing update of the particular item.
I hope it help, if you have better solution then please have your answer.
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)})