puzzy.x
puzzy.x

Reputation: 61

How to store data under specific user id? Angular&Firebase

it's been a while. My question is how to store data in realtime database (firebase) by current logged in user id, so when I log in from another account, I can't see that data (only my own). This is how I do it now: employee.service.ts:

@Injectable({
providedIn: 'root'
})
export class EmployeeService {
userId: string;

constructor(public firebase: AngularFireDatabase, private datePipe: DatePipe, private afu: 
AngularFireAuth, public clientService: ClientService, public contractsService: ContractsService, 
public maintainerService: MaintainerService) {
  this.afu.authState.subscribe(user=>{
      if(user) this.userId=user.uid;
  })
}

employeeList: AngularFireList<any>;
clientList: AngularFireList<any>;
maintainerList: AngularFireList<any>;
contractList: AngularFireList<any>;
array=[];

form: FormGroup=new FormGroup({
$key: new FormControl(null),
sifra: new FormControl(''),
caseName: new FormControl(''),
department: new FormControl(''),
startDate: new FormControl(new Date()),
startTime: new FormControl(''),
finishTime: new FormControl(''),
isPermanent: new FormControl(false), //nije obavezno
description: new FormControl(''),
remark: new FormControl(''), //nije obavezno
serviceType: new FormControl('1'),
isReplaceable: new FormControl(''),
maintainer: new FormControl(''),
contracts: new FormControl(''),
dnevnica: new FormControl(''),
client: new FormControl('')
});
initializeFormGroup(){
this.form.setValue({
$key: null,
sifra: '',
caseName: '',
department: '',
startDate: '',
startTime: '',
finishTime: '',
isPermanent: false,
description: '',
remark: '',
serviceType: '1',
isReplaceable: '',
maintainer: '',
contracts: '',
dnevnica: '',
client: ''
});
}

getEmployees(){
this.employeeList=this.firebase.list(`employees/${this.userId}`);
return this.employeeList.snapshotChanges();
}

And in my compoent file:

 ngOnInit(): void {

 this.service.getEmployees().subscribe(
 list=>{
  let array = list.map(item=>{
    let clientName=this.clientService.getClientName(item.payload.val()['client']);
    let maintainerName=this.maintainerService.getMaintainerName(item.payload.val()['maintainer']);
    return{
      $key: item.key,
      clientName,
      maintainerName,
      ...item.payload.val()
    };
  });
  this.listData= new MatTableDataSource(array);
  this.listData.sort=this.sort;
  this.listData.paginator=this.paginator;
  this.listData.filterPredicate=(data, filter)=>{
    return this.displayColumns.some(ele=>{
      return ele != 'actions' && data[ele].toLowerCase().indexOf(filter) != -1;
    });
  }
});
}

When I login for the first time, everything is good. When I refresh page, all my keep disappearing! It's pretty strange, since my data is still in my database but if I click back button on my browser and enter my component again, data is there again! Thanks in advance.

Upvotes: 2

Views: 536

Answers (1)

Brian Burton
Brian Burton

Reputation: 3842

That is because onAuthStatusChanged(), which is what authState proxies, returns a trinary value, not binary.

Since you're using a truthy check to determine if the user is authenticated, you've created a race condition because you're not waiting for the SDK to fully initialize.

constructor(private afu: AngularFireAuth) {
  this.afu.authState.subscribe(user=>{
      if(user) this.userId=user.uid;
  })
}

Since Firebase Auth is asynchronous, the value returned from authState or onAuthStatusChanged can be one of three values:

  • undefined: The JS SDK has initialized but hasn't checked the user's authentication status yet.
  • null: The user is unauthenticated.
  • User Object: The user is authenticated.

What you need to do is wait until authState returns either null or User like this:

enum AuthState {
  UNKNOWN,
  UNAUTHENTICATED,
  AUTHENTICATED
}

// This subject will store the user's current auth state
private _state = new BehaviorSubject<AuthState>(AuthState.UNKNOWN);

constructor(private afu: AngularFireAuth) {
  this.afu.authState.subscribe(user=>{
      if (typeof user === 'undefined') {
         // Do nothing because the user's auth state is unknown
         return;
      } else if (user === null) {
         // User is unauthenticated
         this._state.next(AuthState.UNAUTHENTICATED);
      } else {
         // User is authenticated
         this.userId = user.uid;
         this._state.next(AuthState.AUTHENTICATED);
      }
  })
}

// Public method to monitor user's auth state
public state$(): Observable {
  return this._state.asObservable();
}

Then in your component you need to subscribe to the state$() observable before calling getEmployees().

ngOnInit(): void {
  this.service.state$().subscribe((state: AuthState) => {
    // We don't know what the user's auth state is, so exit waiting for an update
    if (state === AuthState.UNKNOWN) {
      return;
    } else if (state === AuthState.UNAUTHENTICATED) {
      // User is unauthenticated so redirect to login or whatever
    } else {
      // User is authenticated, so now we can call getEmployees()
      this.service.getEmployees().subscribe(...);
    }
  });
}

Upvotes: 3

Related Questions