Get data from Firebase using angularfire2 (The doc example) - javascript

I'm trying to get the database from Firebase.
I have walked through this tutorial.
After I run ng serve nothing happened and I have this error in the console:
[2018-05-21T12:25:48.364Z] #firebase/firestore: Firestore (5.0.3): Could not reach Firestore backend.
environment.ts:
export const environment = {
production: false,
firebase: {
apiKey: "AIzaSyCip0O3rjU6AXHUKZg7Z26hpLZThTfStsA",
authDomain: "clientpanel-c4a89.firebaseapp.com",
databaseURL: "https://clientpanel-c4a89.firebaseio.com",
projectId: "clientpanel-c4a89",
storageBucket: "clientpanel-c4a89.appspot.com",
messagingSenderId: "894070096713"
}
};
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
// FIREBASE / ANGULARFIER2
import { environment } from '../environments/environment';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { AngularFireStorageModule } from 'angularfire2/storage';
import { AngularFireAuthModule } from 'angularfire2/auth';
// COMPONENTS
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireStorageModule,
AngularFireAuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '#angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
items: Observable<any[]>;
constructor(db: AngularFirestore) {
this.items = db.collection('/client').valueChanges();
}
}
app.component.html:
<h2>The list</h2>
<ul>
<li class="text" *ngFor="let item of items | async">
{{item.email}}
</li>
</ul>
And finally, This is My Firebase

Your screenshot shows that you are using the firebase Real-time Database, but your code uses the firebase Cloud Firestore.
Change AngularFirestore to AngularFireDatabase.
Working example with your database: https://stackblitz.com/edit/so002
-OR-
Move your data to the Cloud Firestore

Related

Angularfire Appcheck not initialized correctly

I am using the angular fire 7.3 (modular) and is really unclear how to setup Appcheck. I am gettin a "Missing or insufficient permissions." error and as I immagined Appcheck is blocking all calls for storage and firestore.
I have seen the code sample here
and have configure the enviroment variables like shown here
I have configured the app module similarly to how they suggested to do here, except that I am not using emulators
but it still acts as if the initialization didn't go through for what concerns Appcheck, both locally and on the deployed version. (both localhost and the domain have been regisred on recaptcha)
Obviously the recaptcha V3 site key I used is correct and has been setup on firebase as well. I did it before on a previous React project which at least for that part worked similarly but at least requests were going through.
...What am I missing?
I saw there is a post showing to essentially initialize firebase like you would do without angularfire but this would end up in having 2 firebase apps running and this sounds really hacky and suboptimal.
I wish their documentation said something about Appcheck...
app-module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MenuComponent } from './components/menu/menu.component';
import { LayoutComponent } from './components/layout/layout.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {MatIconModule} from "#angular/material/icon";
import { HeroComponent } from './components/hero/hero.component';
import { PagenotfoundComponent } from './components/pagenotfound/pagenotfound.component';
import {RouterModule} from "#angular/router";
import { initializeApp,provideFirebaseApp } from '#angular/fire/app';
import { environment } from '../environments/environment';
import { provideAnalytics,getAnalytics,ScreenTrackingService,UserTrackingService } from '#angular/fire/analytics';
import { provideAuth,getAuth } from '#angular/fire/auth';
import { provideFirestore,getFirestore } from '#angular/fire/firestore';
import { provideFunctions,getFunctions } from '#angular/fire/functions';
import { provideStorage,getStorage } from '#angular/fire/storage';
import { LoginComponent } from './components/login/login.component';
import { AppcheckComponent } from './components/appcheck/appcheck.component';
import { ReleaseComponent } from './components/release/release.component';
import { PreloadComponent } from './components/preload/preload.component';
let resolvePersistenceEnabled: (enabled: boolean) => void;
export const persistenceEnabled = new Promise<boolean>(resolve => {
resolvePersistenceEnabled = resolve;
});
#NgModule({
declarations: [
AppComponent,
MenuComponent,
LayoutComponent,
HeroComponent,
PagenotfoundComponent,
LoginComponent,
AppcheckComponent,
ReleaseComponent,
PreloadComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatIconModule,
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAnalytics(() => getAnalytics()),
provideAuth(() => getAuth()),
provideFirestore(() => getFirestore()),
provideFunctions(() => getFunctions()),
provideStorage(() => getStorage()),
],
providers: [
ScreenTrackingService,UserTrackingService
],
bootstrap: [AppComponent]
})
export class AppModule { }
appcheck-component
import { Component, OnInit } from '#angular/core';
import { getToken, AppCheck } from '#angular/fire/app-check';
import { traceUntilFirst } from '#angular/fire/performance';
import { EMPTY, from, Observable } from 'rxjs';
import { keepUnstableUntilFirst } from '#angular/fire';
import { share } from 'rxjs/operators';
#Component({
selector: 'app-app-check',
template: `
<p>
App Check!
<code>{{ (change$ | async)?.token | slice:0:12 }}<ng-container *ngIf="(change$ | async) !== null">…</ng-container></code>
</p>
`,
styles: []
})
export class AppcheckComponent implements OnInit {
readonly change$: Observable<any>;
constructor(appCheck: AppCheck) {
if (appCheck) {
this.change$ = from(getToken(appCheck)).pipe(
traceUntilFirst('app-check'),
keepUnstableUntilFirst,
share(),
);
} else {
this.change$ = EMPTY;
}
}
ngOnInit(): void {
}
}
enviroment variables
export const environment = {
firebase: {
apiKey: "...",
authDomain: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
},
recaptcha3SiteKey: '...',
production: false
};
Version Info:
Anglular 13.1
Firebase 9.8
AngularFire 7.3 (modular)
Just add the AppCheck provider to AppModule imports as you did with all the other ones (Firestore, Functions, etc).
import { initializeAppCheck, provideAppCheck, ReCaptchaV3Provider } from '#angular/fire/app-check'
...
provideAppCheck(() =>
initializeAppCheck(undefined, {
provider: new ReCaptchaV3Provider(environment.recaptchaSiteKey),
isTokenAutoRefreshEnabled: true,
})
),

Service not found in NativeScript Angular

I am new to Angular nativescript, I created a service using the "ng generate service" command in my native angular application, but when importing the service I get the error that the module cannot be found
app.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptModule, NativeScriptHttpClientModule } from "#nativescript/angular";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from './components/login/login.component';
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers: [],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
ApiBackRequestService.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiBackRequestService {
constructor(
private http: HttpClient) {
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
#Component({
selector: 'ns-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
pokemon = [];
constructor(private api: ApiBackRequestService) { }
ngOnInit(): void {
}
}
Thanks
Is it a code-sharing project? in the Login.component.ts file just add # before the src.
change
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
to
import { ApiBackRequestService } from '#src/app/services/api-back-request.service';
this solved my problem
import { ApiBackRequestService } from '../../services/api-back-request.service';

Setting up and inserting data in PouchDb on Ionic 2

Hi Guys im completely new to Ionic 2,
But i know js/ts and all that fun stuff already. Now i want to use PouchDb in my ionic app here is my home.ts file:
import { Component } from '#angular/core';
import * as PouchDB from 'pouchdb';
import cordovaSqlitePlugin from 'pouchdb-adapter-cordova-sqlite';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
}
PouchDB.plugin(cordovaSqlitePlugin);
var db = new PouchDB('test', { adapter: 'cordova-sqlite' });
function setData(data) {
var todo = {
title: data,
completed: false
};
db.post(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
function getData() {
console.log(db.allDocs);
}
Here is my first problem var db = new PouchDb....is no fuction when I put in a on startup function i get an error because my "setData" function doesnt know what "db" is. How can i fix that? And is my importing stuff right?
Next question do i have to import that stuff in my app.module.ts file too? an do i need a provider?
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
I think thats everything for now. Thank you for your help
First, you need to install the SQLite provider.
Here is a tutorial for setting up the PouchDb In Ionic Using SQLite as the database.
https://gonehybrid.com/how-to-use-pouchdb-sqlite-for-local-storage-in-ionic-2/
If you need more help, just comment and I will improve the answer.

ERROR while adding custom module to parent app module in angular

I am trying to add new module to make my angular application more modular and for lazy loading.
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule,BrowserXhr } from "#angular/http";
import { LabService } from './lab/lab.service';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { OphistoryModule } from './Ophistory/ophistory.Module' //after adding this module ERROR is thrown
#NgModule({
imports:[
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: 'labDetails/:labName',component:LabDetailsComponent},
{path:'showRoboLog/:labName',component:RoboLogComponent},
{path:'',component:LabComponent}
]),
OphistoryModule
],
declarations: [
AppComponent
],
bootstrap:[ AppComponent ]
})
export class AppModule {}
app.component
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { LabComponent } from './lab/lab.component';
import { LabService } from './lab/lab.service';
#Component({
selector: 'my-app',
template: `
<router-outlet></router-outlet>
`,
providers: [LabService]
})
export class AppComponent {
constructor() {
}
pageTitle: string = 'ABC';
}
The problem I am facing after adding the module OphistoryModule is an error message saying
my-app' is not a known element:
But when I give the same name to the selector of my newly added module it is working fine.
Here are the custom module and component
ophistory.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser'
import { OphistoryComponent } from './ophistory.component'
import {CommonModule} from '#angular/common'
#NgModule({
imports: [RouterModule.forChild([
{path: 'test',component:OphistoryComponent}
]),CommonModule],
declarations:[OphistoryComponent]
})
export class OphistoryModule {}
ophistory.component
import { Component } from '#angular/core'
import { LabService } from '../lab/lab.service'
#Component({
selector:'my-ap',
templateUrl:'./ophistory.component.html'
})
export class OphistoryComponent {
constructor (private _service:LabService){}
}
Can anyone confirm if it is a bug in angular 2 or any other solution you have?

Storage get() never returning value in ionic 2

Learning ionic 2, particularly using Storage.
So, I just created a blank app:
ionic start storagetest blank --v2
Following this the docs:
cordova plugin add cordova-sqlite-storage --save
npm install --save #ionic/storage
Then, my app.module.ts looks like this:
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
And then went ahead to home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, storage: Storage) {
storage.ready().then(() => {
storage.set('name', 'Max');
storage.get('name').then((val) => {
console.log('Your name is', val);
})
});
}
}
There is nothing in the javascript log. It appears that get() is never returning the value. However, ready() does work, as I have put a console.log() in it.
What is wrong then?
I am running the app on Chrome, Mac OS.
storage.set is asynchronous and returns a promise.So value may not be set when get().then() is called. Try:
storage.ready().then(() => {
storage.set('name', 'Max').then(()=>
storage.get('name').then((val) => {
console.log('Your name is', val);
});
);
});
You have no error handler in then or catch() method which is probably why nothing is logged.

Categories

Resources