如何在特定用户ID下存储数据?Angular& Firebase [英] How to store data under specific user id? Angular&Firebase

查看:62
本文介绍了如何在特定用户ID下存储数据?Angular& Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一段时间了.我的问题是如何通过当前登录的用户ID将数据存储在实时数据库(firebase)中,所以当我从另一个帐户登录时,看不到该数据(只有我自己的数据).我现在是这样的:employee.service.ts:

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();
}

在我的文件中:

 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.

推荐答案

这是因为 authState 代理的 onAuthStatusChanged()返回一个三进制值,而不是二进制.

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

由于您要使用真实检查来确定用户是否已通过身份验证,因此您创建了竞争条件,因为您没有等待SDK完全初始化.

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;
  })
}

由于Firebase身份验证是异步的,因此从 authState onAuthStatusChanged 返回的值可以是以下三个值之一:

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

  • 未定义 :JS SDK已初始化,但尚未检查用户的身份验证状态.
  • null :用户未经身份验证.
  • 用户对象 :用户已通过身份验证.

您需要做的就是等到 authState 返回 null User 像这样:

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();
}

然后在您的组件中,需要先调用可观察的 state $(),然后再调用 getEmployees().

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(...);
    }
  });
}

这篇关于如何在特定用户ID下存储数据?Angular&amp; Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆