I've been doing some research on Google and StackOverflow to try and troubleshoot this error, but I'm still having trouble getting it fixed. Can anyone provide assistance?
Below is the content of my auth-service.ts file:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { LoginService } from './login.service';
import { User } from '../interfaces/Ilogin';
@Injectable({
providedIn: 'root'
})
export class AuthService implements CanActivate {
user: User;
constructor(public loginService: LoginService, public router: Router) {}
canActivate(): boolean {
this.loginService.loggedIn.subscribe(next => {
this.user = next;
});
if (this.user) {
return true;
}
this.router.navigate(['home']);
return false;
}
}
Next, let's take a look at my login.component.ts file:
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { LoginService } from '../services/login.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { User } from '../interfaces/Ilogin';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
user = {} as User;
constructor(
public dialogRef: MatDialogRef<LoginComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private loginService: LoginService,
private fb: FormBuilder,
private router: Router) {}
ngOnInit() {
this.loginForm = this.fb.group({
mobileNumber: [''],
password: ['']
})
}
login(){
if (this.loginForm.valid){
this.user.mobileNumber = this.loginForm.value.mobileNumber;
this.loginService.loggedIn.next(this.user);
this.onNoClick();
}
}
onNoClick(): void {
this.dialogRef.close();
}
}
Moving on to my Ilogin.ts interface file:
export interface User {
mobileNumber: string;
}
Lastly, here is my login.service.ts file:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { User } from '../interfaces/Ilogin';
@Injectable({
providedIn: 'root'
})
export class LoginService {
user: User;
loggedIn = new BehaviorSubject(this.user);
constructor() { }
isLoggedIn(): boolean {
console.log(this.loggedIn);
return true;
}
}
The specific error message you're receiving is:
src/app/services/login.service.ts:10:39 - error TS2729: Property 'user' is used before its initialization.
loggedIn = new BehaviorSubject(this.user); ~~~~
src/app/services/login.service.ts:9:3 user: User; ~~~~ 'user' is declared here.