Hi im new working with angular so im following a youtube tutorial to build a chat.
This project on owners github-> https://github.com/wesdoyle/base-chat
I tried to add AngularFireDatabase to providers its still not working.
I don't know why i get this error when i try to login.
That's my app.module.ts file:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { ChatFormComponent } from './chat-form/chat-form.component';
import { ChatroomComponent } from './chatroom/chatroom.component';
import { FeedComponent } from './feed/feed.component';
import { MessageComponent } from './message/message.component';
import { LoginFormComponent } from './login-form/login-form.component';
import { SignupFormComponent } from './signup-form/signup-form.component';
import { NavbarComponent } from './navbar/navbar.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserItemComponent } from './user-item/user-item.component';
import { ChatService } from './services/chat.service';
import { AuthService } from './services/auth.service';
import { appRoutes } from '../routes';
import { environment } from '../environments/environment';
#NgModule({
declarations: [
AppComponent,
ChatFormComponent,
ChatroomComponent,
FeedComponent,
MessageComponent,
LoginFormComponent,
SignupFormComponent,
NavbarComponent,
UserListComponent,
UserItemComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
FormsModule,
AngularFireModule,
AngularFireDatabaseModule,
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebase)
],
providers: [AuthService,ChatService],
bootstrap: [AppComponent]
})
export class AppModule { }
And that's the login-form.component.ts where i throw the error.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { AngularFireDatabase} from 'angularfire2/database';
import { Router } from '#angular/router';
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent {
email: string;
password: string;
errorMsg: string;
constructor(private authService: AuthService, private router: Router) { }
login() {
console.log('login() called from login-form component');
this.authService.login(this.email, this.password)
.catch(error => this.errorMsg = error.message);
}
}
This is the chat.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable,of } from 'rxjs';
import { AuthService } from '../services/auth.service';
import * as firebase from 'firebase/app';
import { ChatMessage } from '../models/chat-message.model';
#Injectable()
export class ChatService {
user: firebase.User;
chatMessages: FirebaseListObservable<ChatMessage[]>;
chatMessage: ChatMessage;
userName: Observable<string>;
constructor(
private db: AngularFireDatabase,
private afAuth: AngularFireAuth
) {
this.afAuth.authState.subscribe(auth => {
if (auth !== undefined && auth !== null) {
this.user = auth;
}
this.getUser().subscribe(a => {
this.userName = a.displayName;
});
});
}
getUser() {
const userId = this.user.uid;
const path = `/users/${userId}`;
return this.db.object(path);
}
getUsers() {
const path = '/users';
return this.db.list(path);
}
sendMessage(msg: string) {
const timestamp = this.getTimeStamp();
const email = this.user.email;
this.chatMessages = this.getMessages();
this.chatMessages.push({
message: msg,
timeSent: timestamp,
userName: this.userName,
email: email });
}
getMessages(): FirebaseListObservable<ChatMessage[]> {
// query to create our message feed binding
return this.db.list('messages', {
query: {
limitToLast: 25,
orderByKey: true
}
});
}
getTimeStamp() {
const now = new Date();
const date = now.getUTCFullYear() + '/' +
(now.getUTCMonth() + 1) + '/' +
now.getUTCDate();
const time = now.getUTCHours() + ':' +
now.getUTCMinutes() + ':' +
now.getUTCSeconds();
return (date + ' ' + time);
}
}
In your chart.service.ts you have a wrong import which is depreciated,
Change
From
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated';
To
import { AngularFireDatabase,FirebaseListObservable,FirebaseObjectObservable } from 'angularfire2/database';
You forgot to provide your service in the Component
#Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css'],
providers: [AuthService]
})
hope this helps.
Related
I'm doing an angular project using the NZ-Zorro library and I'm having a hard time finding what are these parameters that aren't being solved from NzModalRef, when I try to run the test --code-coverage to do the tests. I get this error.
Error: NG0204: Can't resolve all parameters for NzModalRef: (?, ?, ?).
That's my .spec
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { MinistryService } from './../../ministry.service';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import {
NzModalModule,
NzModalService,
NzModalRef,
} from 'ng-zorro-antd/modal';
import { MembersService } from '../../members.service';
import { ComponentFixture } from '#angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController,
} from '#angular/common/http/testing';
import {
UntypedFormBuilder,
UntypedFormGroup,
Validators,
FormsModule,
} from '#angular/forms';
import { TestBed } from '#angular/core/testing';
import { HttpClient } from '#angular/common/http';
import { FormNewMemberComponent } from './form-new-member.component';
import { ReactiveFormsModule } from '#angular/forms';
describe('FormNewMemberComponent', () => {
let component: FormNewMemberComponent;
let fixture: ComponentFixture<FormNewMemberComponent>;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
let fb: UntypedFormBuilder;
let validateForm: UntypedFormGroup;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormNewMemberComponent],
imports: [
HttpClientTestingModule,
ReactiveFormsModule,
NzModalModule,
FormsModule,
BrowserAnimationsModule,
],
providers: [
MembersService,
NzModalService,
HttpClient,
Validators,
NzModalRef,
MinistryService,
NzNotificationService,
UntypedFormBuilder,
],
}).compileComponents();
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
fb = TestBed.inject(UntypedFormBuilder);
fixture = TestBed.createComponent(FormNewMemberComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
My .ts
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Ministry } from './../../ministry/ministry.model';
import { MemberPageComponent } from './../member-page.component';
import { MembersService } from '../../members.service';
import { Component, OnInit } from '#angular/core';
import {
UntypedFormBuilder,
UntypedFormControl,
UntypedFormGroup,
Validators,
} from '#angular/forms';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { MinistryService } from '../../ministry.service';
#Component({
selector: 'app-form-new-member',
templateUrl: './form-new-member.component.html',
styleUrls: ['./form-new-member.component.scss'],
})
export class FormNewMemberComponent implements OnInit {
validateForm!: UntypedFormGroup;
isVisible = false;
pagina!: MemberPageComponent;
members: any;
ministrys: Ministry[] = []
listOfMinistrys!: Ministry[]
createNotificationSuccess(type: string): void {
this.notification.create(
type,
'Sucesso!',
'Membro adicionado.',
{nzDuration: 2000}
);
}
createNotificationError(type: string): void {
this.notification.create(
type,
'Erro!',
'Membro não foi adicionado.',
{nzDuration: 2000}
);
}
constructor(
private fb: UntypedFormBuilder,
private membersService: MembersService,
private nzModalRef: NzModalRef,
private notification: NzNotificationService,
private ministryService: MinistryService
) {}
ngOnInit(): void {
this.validateForm = this.fb.group({
email: [null, [Validators.email, Validators.required]],
password: [null, [Validators.required]],
checkPassword: [null, [Validators.required, this.confirmationValidator]],
name: [null, [Validators.required]],
phoneNumber: [null, [Validators.required]],
cpf: [null, [Validators.required]],
rg: [null, [Validators.required]],
ministry: [null, [Validators.required]],
address: [null, [Validators.required]],
});
this.showMinistry()
}
submitForm(): void {
if (this.validateForm.valid) {
this.membersService.create(this.validateForm.value).subscribe(
(success) => {
this.createNotificationSuccess('success')
this.destroyModal();
},
(error) => {
this.createNotificationError('error')
}
);
} else {
Object.values(this.validateForm.controls).forEach((control) => {
if (control.invalid) {
control.markAsDirty();
control.updateValueAndValidity({ onlySelf: true });
}
});
}
}
updateConfirmValidator(): void {
Promise.resolve().then(() =>
this.validateForm.controls['checkPassword'].updateValueAndValidity()
);
}
confirmationValidator = (
control: UntypedFormControl
): { [s: string]: boolean } => {
if (!control.value) {
return { required: true };
} else if (control.value !== this.validateForm.controls['password'].value) {
return { confirm: true, error: true };
}
return {};
};
destroyModal(): void {
this.nzModalRef.destroy({ newMember: this.validateForm.value });
}
showMinistry(){
this.ministryService.getMinistrys().subscribe((data) => {
this.ministrys = data;
this.listOfMinistrys = [...this.ministrys];
});
}
}
My service
import { Injectable } from '#angular/core';
import { Member } from './member-page/members.model';
import { Observable, take} from 'rxjs';
import { HttpClient } from '#angular/common/http';
const apiMembers = 'http://localhost:3000/membrosBd';
#Injectable({
providedIn: 'root',
})
export class MembersService {
constructor(private http: HttpClient) { }
getMembers(): Observable<Member[]> {
return this.http.get<Member[]>(apiMembers)
}
create(member: Member): Observable<Member>{
return this.http.post<Member>(apiMembers, member).pipe(take(1));
}
}
And my module
import { NzNotificationModule } from 'ng-zorro-antd/notification';
import { HttpClientModule } from '#angular/common/http';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NzPaginationModule } from 'ng-zorro-antd/pagination';
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MemberPageComponent } from './member-page/member-page.component';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzAutocompleteModule } from 'ng-zorro-antd/auto-complete';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzDropDownModule } from 'ng-zorro-antd/dropdown';
import { NzModalModule, NzModalRef } from 'ng-zorro-antd/modal';
import { FormNewMemberComponent } from './member-page/form-new-member/form-new-member.component';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { MinistryComponent } from './ministry/ministry.component';
import { NzListModule } from 'ng-zorro-antd/list';
#NgModule({
declarations: [
MemberPageComponent,
FormNewMemberComponent,
MinistryComponent,
],
imports: [
CommonModule,
NzTableModule,
NzPaginationModule,
NzAutocompleteModule,
NzButtonModule,
NzInputModule,
NzIconModule,
NzDropDownModule,
ReactiveFormsModule,
HttpClientModule,
FormsModule,
NzModalModule,
NzFormModule,
NzSelectModule,
NzNotificationModule,
NzListModule,
],
providers: [NzModalRef],
exports: [
MemberPageComponent
]
})
export class MembrosModule { }
I thank anyone who can help me.
hope that the nzmodalref parameters can be solved
I faced with next error and cannot understand how to resolve it.
Error: Can't resolve all parameters for LoginPage: ([object Object], [object Object], [object Object], ?).
I've checked almost every topic here and have tried multiple ways to resolve it but still can't beat it already second day.
Login.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,AlertController } from 'ionic-angular';
import { AuthProvider } from '../../providers/auth/auth';
import { TabsPage } from '../tabs/tabs';
/**
* Generated class for the LoginPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
email:string = '';
password:string = '';
errorMsg:string;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
public alertCtrl: AlertController
public authService: AuthProvider,
) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
errorFunc(message){
let alert = this.alertCtrl.create({
title: 'oops!',
subTitle: message,
buttons: ['OK']
});
alert.present();
}
myLogIn(){
if (this.email.trim() !=='' ) {
console.log(this.email.trim() + " " + this.password.trim() )
if (this.password.trim() === '') {
this.errorFunc('Please put your password')
}
else{
let credentials = {
email: this.email,
password: this.password
};
this.authService.login(credentials).then((result) => {
console.log(result);
this.navCtrl.setRoot(TabsPage);
}, (err) => {
console.log(err);
this. errorFunc('Wrong credentials ! try again')
console.log("credentials: "+JSON.stringify(credentials))
});
}
}
else{
this. errorFunc('Please put a vaild password ! for ex:(123456)')
}
}
myLogOut(){
this.authService.logout();
}
}
Auth.ts
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
import { Http , Headers } from '#angular/http';
import { TabsPage } from '../../pages/tabs/tabs';
#Injectable()
export class AuthProvider {
rootPage:any = TabsPage;
public token:any;
constructor(public storage:Storage ,public http: Http) {
console.log('Hello AuthProvider Provider');
}
login(credentials){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('Content-type','application/json');
headers.append('X-Requested-With','XMLHttpRequest');
this.http.post('http://127.0.0.1:8000/api/auth/login', JSON.stringify(credentials), {
headers: headers})
.subscribe(res => {
let data = res.json();
this.token = data.token;
localStorage.setItem('token',data.access_token);
resolve(data);
}, (err) => {
reject(err);
}); });
}
checkAuthentication(){
return new Promise((resolve, reject) => {
this.storage.get('token').then((value) => {
this.token = value;
resolve(this.token)
})
});
}
logout(){
localStorage.setItem('token','');
}
}
app.moodule.ts
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 { IonicStorageModule } from '#ionic/storage';
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 { LoginPage } from '../pages/login/login';
import { AddPage } from '../pages/add/add';
import { AuthProvider } from '../providers/auth/auth';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HttpModule } from '#angular/http';
import { ComplaintProvider } from '../providers/complaint/complaint';
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
AddPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot(),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
AddPage
],
providers: [
StatusBar,
SplashScreen,
AuthProvider,
ComplaintProvider,
{provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {}
You seem to be having a classic circular reference going around. You have the "TabsPage" imported in both Auth.ts & in your "LoginPage.ts".
A Classic Circular Reference.
Try removing the TabsPage from Auth.ts. In general, it is best if you have your components do very specific things so that you have a granular code and avoid such circular reference issues.
I have a payment page with payment component as -
import { Component, OnInit } from '#angular/core';
import { PayPalConfig, PayPalEnvironment, PayPalIntegrationType } from 'ngx-paypal';
import { AppService } from '../app.service';
import { Payment } from '../models/payment.model';
import { Router } from '#angular/router';
#Component({
selector: 'app-payment',
templateUrl: './payment.component.html',
styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit {
//totalpay:number;
payment:Payment;
changesSaved=false;
constructor(private appservice:AppService,private router:Router) { }
ngOnInit() {
this.initConfig();
}
hasChanges(){
return true;
} }
Now I want to prompt user if he tries to move back or try to click any link ,without clicking on paypal payment button in payment component ,I have used Candeactivate by making paymentguard.ts
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { PaymentComponent } from './payment/payment.component';
import { PaymentGuard} from './payment/payment.guard';
#Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<PaymentComponent> {
canDeactivate(target: PaymentComponent) {
if (target.hasChanges()) {
return window.confirm('Do you really want to cancel?');
}
return true;
}
}
And this is my routing in app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { BannerComponent } from './banner/banner.component';
import { ProductsComponent } from './products/products.component';
import { BodyComponent } from './body/body.component';
import { BestsellersComponent } from './bestsellers/bestsellers.component';
import { FooterComponent } from './footer/footer.component';
import { BenefitComponent } from './benefit/benefit.component';
import { CombinedComponent } from './combined/combined.component';
import { CartComponent } from './cart/cart.component';
import { StorageServiceModule} from 'angular-webstorage-service';
import { FormsModule } from '../../node_modules/#angular/forms';
import { NgxPayPalModule } from 'ngx-paypal';
import { HttpClientModule } from '#angular/common/http';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { PaymentComponent } from './payment/payment.component';
import { AuthGuard } from './auth.guard';
import { FlashMessagesModule } from 'angular2-flash-messages';
import { FinalstatusComponent } from './finalstatus/finalstatus.component';
import { ConfirmDeactivateGuard } from './payment.guard';
import { PaymentfailComponent } from './paymentfail/paymentfail.component';
const routes: Routes = [
{ path: 'cart', component: CartComponent },
{ path: 'about', component: AboutComponent },
{ path: '', component: CombinedComponent },
{ path: 'payment', component: PaymentComponent,canActivate:[AuthGuard],canDeactivate[ConfirmDeactivateGuard]},
{ path: 'orderstatus', component: FinalstatusComponent,canActivate:[AuthGuard] },
{ path: 'paymentfail', component: PaymentfailComponent,canActivate:[AuthGuard] },
{ path: 'contact', component: ContactComponent },
];
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
BannerComponent,
ProductsComponent,
BodyComponent,
BestsellersComponent,
FooterComponent,
BenefitComponent,
CombinedComponent,
CartComponent,
AboutComponent,
ContactComponent,
PaymentComponent,
FinalstatusComponent,
PaymentfailComponent,
],
imports: [
BrowserModule,
RouterModule.forRoot(routes),
StorageServiceModule,
FormsModule,
NgxPayPalModule,
HttpClientModule,
FlashMessagesModule.forRoot()
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
I don't know why it is not working ,any idea how to achieve it???
Your CanDeactivate route guard must return one of: boolean, Promise, Observable.
In your case, it is best you use the later because your rely on the user taking an action to decide if CanDeactivate care run or not. This makes your guard asynchronous.
Because the method must always return the same type, the !hasChanges() myst also return an observable.
Try this code below:
import { Observable, create } from 'rxjs';
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { PaymentComponent } from './payment/payment.component';
import { PaymentGuard} from './payment/payment.guard';
#Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<PaymentComponent> {
canDeactivate(target: PaymentComponent): Observable<boolean> {
return Observable.create(function(observer) {
if (!target.hasChanges()) {
observer.next(true);
} else if(window.confirm('Do you really want to cancel?')) {
observer.next(true);
} else {
observer.next(false);
}
});
}
}
I hope this helps!
Edit: I moved everything inside of the observer
Authentication doesn't seem to persist after page has been refreshed. Whenever I login, it successfully redirects me. but, when i refreshed, accessing is not possible anymore.
here is the auth guard
router
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { FIREBASECONFIG as firebaseConfig } from './config/firebase-config';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard.service';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];
#NgModule({
declarations: [
AppComponent,
NavComponent,
HomeComponent,
GalleryComponent,
FooterComponent,
],
imports: [
FormsModule,
BrowserModule,
AppRoutingModule,
NgxCarouselModule,
NgbModule.forRoot(),
ScrollToModule.forRoot(),
RouterModule.forRoot(routes),
AnimateOnScrollModule.forRoot(),
HttpClientModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule,
AngularFireDatabaseModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
exports: [
TranslateModule
],
providers: [AngularFireDatabase, AuthService, AuthGuard],
bootstrap: [AppComponent]
})
auth.guard.ts
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable, OnInit } from '#angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '#angular/router';
#Injectable()
export class AuthGuard implements CanActivate {
public user = null;
constructor(private fireauth: AngularFireAuth, private router: Router) {
this.fireauth.auth.onAuthStateChanged((user) => {
if (user) {
this.user = this.fireauth.auth.currentUser;
}
});
}
ongOnInit() {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
if (this.user) {
return true;
} else {
this.router.navigate(['']);
return false;
}
}
}
the routes are ok according to me, i thing that the problem most be on the auth guard, i guess.
Try this code
constructor(
private router:Router,
public fireauth:AngularFireAuth
){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
return this.fireauth.authState.map((auth) => {
if(auth == null) {
this.router.navigate(['/']);
return false;
} else {
return true;
}
});
}
i think this.fireauth.auth.onAuthStateChanged is used in older versions
Before I ask, I do not speak English very well.
first, I'm #angular#4.3.3 and my typescript version is ~2.3.3
Ask.
I lazy loaded the LoginModule
AppRoute
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login#LoginModule' }
];
export const AppRoutes = RouterModule.forRoot(routes);
and my
AppModule
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutes } from './routing/app.routing';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutes,
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and
LoginModule
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { ErrorCodeService } from '../shared/service/error-code/error-code.service';
import { LoginService } from '../shared/service/login/login.service';
import { LoginComponent } from './login.component';
#NgModule({
imports: [
HttpClientModule,
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: '', component: LoginComponent }
])
],
exports: [],
declarations: [ LoginComponent ],
providers: [
ErrorCodeService,
LoginService,
],
})
export class LoginModule { }
and
LoginService
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorCodeService } from '../error-code/error-code.service';
import { RequestCore } from '../request-core';
#Injectable()
export class LoginService extends RequestCore {
constructor(
protected http: HttpClient,
private errorCode: ErrorCodeService,
) {
super(http, '/Login');
}
public load(userid: string, passwd: string): Observable<any> {
const params = new HttpParams()
.append('id', userid)
.append('passwd', passwd);
return this.get({ params })
.map(res => {
if (res.islogin === 'true') {
return res.sendRedirect;
}
throw new Error(this.errorCode.getErrorMsg(res.reason));
});
}
}
RequestCore
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { HttpOptions } from '../models';
export abstract class RequestCore {
constructor(
protected http: HttpClient,
private url: string,
) {
// 개발 모드에서는 proxy를 위해 url에 /dev 접두어를 붙인다.
if (environment.production === false) {
url = '/dev' + url;
}
}
protected get(options?: HttpOptions): Observable<any> {
return this.http.get(this.url, options);
}
protected post(options?: HttpOptions): Observable<any> {
return this.http.post(this.url, {}, options);
}
}
This is my error
I don't know why I can't DI in LoginService
ReuquestCore Are you making the wrong inheritance?
Teach me
Thank you!
Re:
An error occurs when the first screen is loaded.
When the next hmr is updated, no error occurs.