Angularfire v6 undefined AngularFireStore in Promise - javascript

My login component logs the user in successfully, but then I'd like to create a document for this user in FireStore.
I keep getting an issue loading the AngularFirestore afs in this case.
zone-evergreen.js:659 Unhandled Promise rejection: Cannot read property 'afs' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'afs' of undefined
at onLoginFulfiled (login.component.ts:32)
at ZoneDelegate.invoke (zone-evergreen.js:365)
at Zone.run (zone-evergreen.js:124)
at zone-evergreen.js:851
at ZoneDelegate.invokeTask (zone-evergreen.js:400)
Here is my login component code.
import { Component, OnInit } from '#angular/core';
import { LoginRequest } from './loginRequest';
import { AngularFireAuth } from '#angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '#angular/fire/firestore';
import { auth } from 'firebase/app';
import 'firebase/firestore';
export interface Item { uid: string; }
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginRequest: LoginRequest = { password: '', login: ''};
constructor(public fireAuth: AngularFireAuth, public afs: AngularFirestore) { }
ngOnInit(): void {
}
login(): void {
console.log(this.loginRequest);
this.fireAuth.signInWithEmailAndPassword(this.loginRequest.login, this.loginRequest.password)
.then(this.onLoginFulfiled, this.onLoginRejected);
}
onLoginFulfiled(credential: auth.UserCredential): void {
console.log('Fulfilled: ' + credential);
const uid = credential.user.uid;
const userDocument = this.afs.doc<Item>(`system-users/${uid}`);
userDocument.update({uid});
}
onLoginRejected(reason: any): void {
console.log('Rejected: ' + reason);
}
}
Also my app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { AngularFireModule } from '#angular/fire';
import { AngularFireAnalyticsModule } from '#angular/fire/analytics';
import { AngularFirestoreModule } from '#angular/fire/firestore';
import { environment } from '../environments/environment';
import { LoginComponent } from './login/login.component';
#NgModule({
declarations: [
AppComponent,
PageNotFoundComponent,
LoginComponent
],
imports: [
BrowserModule,
FormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAnalyticsModule,
AngularFirestoreModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Try replacing
.then(this.onLoginFulfiled, this.onLoginRejected);
with
.then(() => this.onLoginFulfiled(), () => this.onLoginRejected());

Related

Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Please add a #Pipe/#Directive/#Component annotation

I writng about create ticket but it happen error.I am stuck in a situation here. I am getting an error like this.
Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Please add a #Pipe/#Directive/#Component annotation.
My add-ticket Component Looks like this
import { Component, OnInit } from '#angular/core';
import { TicketService } from './../../services/ticket.service';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-add-ticket',
templateUrl: './add-ticket.component.html',
styleUrls: ['./add-ticket.component.scss']
})
export class AddTicketComponent implements OnInit {
public ticketForm: FormGroup;
constructor(
public ticketAPI: TicketService,
public fb: FormBuilder
) { }
ngOnInit() {
this.ticketAPI.getTicketsList();
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './pages/login/login.component';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './pages/home/home.component';
import { SignupComponent } from './pages/signup/signup.component';
import { ProfileComponent } from './pages/profile/profile.component';
import { AddTicketComponent } from './pages/add-ticket/add-ticket.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { environment } from 'src/environments/environment';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './guards/auth.guard';
import { from } from 'rxjs';
import { Component } from '#angular/Core';
// Routes
export const router: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'add-ticket', component: AddTicketComponent}
];
#NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
NavbarComponent,
ProfileComponent,
SignupComponent,
AddTicketComponent,
AppRoutingModule,
],
imports: [
FormsModule,
ReactiveFormsModule,
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(router),
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
],
providers: [AuthService, AngularFireDatabase, AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Check your routing module is declared with #NgModule looks # is missing.
Check the components too.
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{
path: '',
loadChildren: () => import('./components/home/home.module').then(m => m.HomeModule)
},
{
path: 'home',
loadChildren: () => import('./components/home/home.module').then(m => m.HomeModule)
},
{
path: 'cars',
loadChildren: () => import('./components/cars-list/cars-list.module').then(m => m.CarsListModule)
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
remove AppRoutingModule from declarations
You have a typo in the import in your app.module.ts file
import { Component } from '#angular/Core';
It's lowercase c, not uppercase
import { Component } from '#angular/core';

Angular Firebase authentication always redirects to home page

In this Angular project which I am practicing through a tutorial,when I try to access pages that require authentication, I am redirected to login page and even the URL changes to http://localhost:4200/login?returnURL=%2Fcheck-out.
But after logging in ,it always redirects to home page irrespective of the links.
app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
import { Router } from '../../node_modules/#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private auth:AuthService, router:Router){
auth.user$.subscribe(user=>{
if(user){
let returnUrl=localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl);
}
});
}
}
auth.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '../../node_modules/angularfire2/auth';
import { Observable } from '../../node_modules/rxjs';
import * as firebase from 'firebase';
import { ActivatedRoute } from '../../node_modules/#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
user$: Observable<firebase.User>;
constructor(private afAuth:AngularFireAuth,private route:ActivatedRoute) {
this.user$=afAuth.authState;
}
login(){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl') ||'/';
localStorage.setItem('returnUrl',returnUrl);
this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
}
logout(){
this.afAuth.auth.signOut();
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule, AngularFireAuth} from 'angularfire2/auth';
import { Observable} from 'rxjs';
import {RouterModule, RouterOutlet, Routes} from '#angular/router';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSucessfulComponent } from './order-sucessful/order-sucessful.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth-guard.service';
export const appRoutes: Routes = [
{path:'',component:HomeComponent},
{path:'products',component:ProductsComponent},
{path:'shopping-cart',component:ShoppingCartComponent},
{path:'login',component:LoginComponent},
{path:'check-out',component:CheckOutComponent,canActivate:[AuthGuard]},
{path:'order-sucessful',component:OrderSucessfulComponent,canActivate:[AuthGuard]},
{path:'my/orders',component:MyOrdersComponent,canActivate:[AuthGuard]},
{path:'admin/products',component:AdminProductsComponent,canActivate:[AuthGuard]},
{path:'admin/orders',component:AdminOrdersComponent,canActivate:[AuthGuard]}
]
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSucessfulComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireDatabaseModule,
NgbModule.forRoot()
],
providers: [AngularFireAuth,AuthService,AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Seems to be in your localStorage.getItem('returnUrl'); always set to root of the application better to first check if there is a value and then remove that value and redirect the user like below:
let returnUrl = localStorage.getItem('returnUrl');
if (returnUrl) {
localStorage.removeItem('returnUrl');
router.navigateByUrl(returnUrl);
}
Hope this will helps you!

Issue with getting a constructor to work when passing a value into it

I have this code:
import {Component, OnInit} from '#angular/core';
import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated';
import {Item} from '../shared/item';
import {ItemService} from '../shared/item.service';
#Component({
selector: 'app-items-list',
templateUrl: './items-list.component.html',
styleUrls: ['./items-list.component.scss']
})
export class ItemsListComponent implements OnInit {
public items: FirebaseListObservable<any[]>;
constructor(private itemSvc: ItemService) {
}
ngOnInit() {
this.items = this.itemSvc.getItemsList({limitToLast: 10});
}
deleteItems() {
this.itemSvc.deleteAll();
}
}
When I try to run it, I get the great and useful ERROR Error: "[object Object]". I was commenting out, until the error went away. It looks like there is something wrong with my constructor, but I have no idea what. Any ideas?
Here's my ItemService:
import {Injectable} from '#angular/core';
import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated';
import {Item} from './item';
#Injectable()
export class ItemService {
private basePath: string = '/items';
items: FirebaseListObservable<Item[]> = null; // list of objects
item: FirebaseObjectObservable<Item> = null; // single object
constructor(private db: AngularFireDatabase) {
}
getItemsList(query = {}): FirebaseListObservable<any[]> {
this.items = this.db.list(this.basePath, {
query: query
});
return this.items;
}
// Return a single observable item
getItem(key: string): FirebaseObjectObservable<Item> {
const itemPath = `${this.basePath}/${key}`;
this.item = this.db.object(itemPath);
return this.item;
}
createItem(item: Item): void {
this.items.push(item)
// .catch(error => this.handleError(error));
}
// Update an existing item
updateItem(key: string, value: any): void {
this.items.update(key, value)
.catch(error => this.handleError(error));
}
// Deletes a single item
deleteItem(key: string): void {
this.items.remove(key)
.catch(error => this.handleError(error));
}
// Deletes the entire list of items
deleteAll(): void {
this.items.remove()
.catch(error => this.handleError(error));
}
// Default error handling for all actions
private handleError(error) {
console.log(error);
}
}
HTML template:
<div *ngFor="let item of items | async" >
<app-item-detail [item]='item'></app-item-detail>
</div>
<!--<button (click)='deleteItems()'>Delete Entire List</button>-->
app.module.ts file:
import {BrowserModule} from '#angular/platform-browser';
import {NgModule} from '#angular/core';
import {RouterModule} from '#angular/router';
import {rootRouterConfig} from './app.routes';
import {AngularFireModule} from 'angularfire2';
import {AngularFirestoreModule} from 'angularfire2/firestore';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {environment} from '../environments/environment';
import {LoginComponent} from './login/login.component';
import {UserComponent} from './user/user.component';
import {RegisterComponent} from './register/register.component';
import {UserResolver} from './user/user.resolver';
import {AuthGuard} from './core/auth.guard';
import {AuthService} from './core/auth.service';
import {UserService} from './core/user.service';
import {ReactiveFormsModule} from '#angular/forms';
import {AppComponent} from './app.component';
import {HomeComponent} from './home/home.component';
import {AboutComponent} from './about/about.component';
import {ItemsListComponent} from './items/items-list/items-list.component';
import {ItemDetailComponent} from './items/item-detail/item-detail.component';
import {ItemFormexportComponent} from './items/item-formexport/item-formexport.component';
import {ItemFormComponent} from './items/item-form/item-form.component';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
UserComponent,
RegisterComponent,
HomeComponent,
AboutComponent,
ItemsListComponent,
ItemDetailComponent,
ItemFormexportComponent,
ItemFormComponent,
],
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot(rootRouterConfig, {useHash: false}),
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule, // imports firebase/firestore, only needed for database features
AngularFireAuthModule, // imports firebase/auth, only needed for auth features
],
providers: [AuthService, UserService, UserResolver, AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule {
}
I'm new to Angular so if I missed anything please let me know, and I'll add it.
You make sure that you import the AngularFireDatabaseModule in your app.module.ts file. Since your service is using the AngularFireDatabase.
Please see the below link for more info.
https://github.com/angular/angularfire2/blob/master/docs/storage/storage.md
import { AngularFireModule } from 'angularfire2';
// for AngularFireDatabase
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
// for AngularFireAuth
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireAuth } from 'angularfire2/auth';
#NgModule({
imports: [
AngularFireModule.initializeApp({ <---- main module
apiKey: ...,
authDomain: '...',
databaseURL: '...',
storageBucket: '...',
messagingSenderId: '...'
}),
AngularFireDatabaseModule, <---- for database
AngularFireAuthModule <---- for auth
]
})

Uncaught TypeError: Cannot read property 'prototype' of undefined at __extends (Subscriber.js:5)

I got this error after ng build and uploading to production server. I'm using angular cli on angular4. All this really started when I added the Route Guard to a feature module. I reverted back to when I had no Guard but the error still persists. When I run ng serve on my local machine I don't get this error.
This is my app module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { HashLocationStrategy, LocationStrategy } from '#angular/common';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
/* Routing Module */
import { AppRoutingModule } from './app-routing.module';
/* Authentication */
import {AuthenticateService} from './authenticate.service';
import {AuthGuard} from './auth.guard';
import {DashboardModule} from './dashboard/dashboard.module';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
DashboardModule,
AppRoutingModule
],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy},
AuthenticateService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
My auth Service:
import { Injectable } from '#angular/core';
import {Response, Headers, Http, RequestOptionsArgs} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticateService {
baseUrl = 'myurl/public';
constructor(private http: Http) { }
register(form) {
return this.http.post(`${this.baseUrl}/register`, form)
.map((response: Response) => {
const user = response.json();
if (user.status) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('loggedUser', JSON.stringify(user));
}
return user;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
login(form): Observable<Response> {
const headersObj = new Headers();
headersObj.set('Content-Type', 'application/json');
const requestArg: RequestOptionsArgs = { headers: headersObj, method: 'POST' };
// const telephone = form.telephone;
// const password = form.password;
return this.http.post(`${this.baseUrl}/login`, form, requestArg)
.map((response: Response) => {
const user = response.json();
if (user.response.status) {
localStorage.setItem('loggedUser', JSON.stringify(user.response));
}
return user.response;
})
.catch((error: any) => Observable.throw(error.json().error || {message: 'Server Error'}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('loggedUser');
}
}
My Route Guard:
import { Injectable } from '#angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
// import {AuthenticateService} from './authenticate.service';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if ((!localStorage.getItem('loggedUser'))) {
// not logged in so redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
} else {
return true;
}
}
}
App routing Module:
import { NgModule } from '#angular/core';
import {RouterModule, Routes} from '#angular/router';
import {LoginComponent} from './login/login.component';
import {RegisterComponent} from './register/register.component';
export const routes: Routes = [
{path: '', redirectTo: 'dashboard', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
Guarded Module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import {FormsModule} from '#angular/forms';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { DashboardComponent } from './dashboard.component';
import { DashboardHomeComponent } from './dashboard-home/dashboard-home.component';
import { UsersComponent } from './users/users.component';
import { TransactionsComponent } from './transactions/transactions.component';
import { UsersService } from './services/users.service';
#NgModule({
imports: [
CommonModule,
FormsModule,
RouterModule,
DashboardRoutingModule
],
exports: [ DashboardComponent ],
declarations: [ DashboardComponent, DashboardHomeComponent, UsersComponent, TransactionsComponent],
providers: [ UsersService ]
})
export class DashboardModule { }
Feature Module Component:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import {DashboardComponent} from './dashboard.component';
import {DashboardHomeComponent} from './dashboard-home/dashboard-home.component';
import {UsersComponent} from './users/users.component';
import {TransactionsComponent} from './transactions/transactions.component';
import {AuthGuard} from '../auth.guard';
export const dashboardRoutes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [ AuthGuard ],
children: [
{path: '', component: DashboardHomeComponent},
{path: 'users', component: UsersComponent},
{path: 'transactions', component: TransactionsComponent}
]}
// {path: 'dashboard', component: DashboardComponent}
];
#NgModule({
imports: [
RouterModule.forChild(dashboardRoutes)
],
exports: [
RouterModule
],
declarations: []
})
export class DashboardRoutingModule { }
I found the error, I imported Router module in my feature module and also in my feature-routing module.

TypeError: Cannot set property stack of [object Object] which has only a getter

When I am trying to use the service in my componenet and declatring it in constructor , I am getting this error TypeError: Cannot set property stack of [object Object] which has only a getter
I have below my code
import { Component } from '#angular/core';
import { FormBuilder,FormGroup} from '#angular/forms';
import { LoginService } from '../../services/login.service';
#Component({
selector: 'login-selector',
templateUrl: './app/components/login/login.component.html',
})
export class LoginComponent {
form:FormGroup;
items:Object;
constructor(
private formBuilder:FormBuilder,
private loginService:LoginService){
}
ngOnInit() {
this.form=this.formBuilder.group({
userName:this.formBuilder.control(''),
password:this.formBuilder.control(''),
remember:this.formBuilder.control(''),
textCaptcha:this.formBuilder.control('')
});
}
onSubmit(loginForm:FormGroup){
this.loginService.getTestJson().subscribe(mediaItems => {
this.items = mediaItems;
});
}
}
Service is
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class LoginService{
constructor(private http: Http) {}
getTestJson(){
return this.http.get('http://geo.groupkt.com/ip/172.217.3.14/json').map(response => {
return response.json();
});
}
}
and app module ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { LoginService } from './services/login.service';
#NgModule({
imports: [ BrowserModule,ReactiveFormsModule ],
declarations: [ AppComponent,LoginComponent ],
bootstrap: [ AppComponent ],
providers:[LoginService]
})
export class AppModule { }
import { HttpModule} from '#angular/http'; in app module ts
and add it in NgModule imports
It is likely you have ngModel in your Html, to do so, you need to be very careful.
You can't just use ngModel by itself in formGroup. It only works with formGroupName

Categories