简体   繁体   中英

How to retrieve AngularList if firebase rules is set to auth !=null

My issue is that I do not know can I retrieve data from firabase using AngularFireList. If I set database rules as with data can be used only by authorized user:

{
  "rules": {
    ".read":  "auth !=null",  // 2021-1-28
    ".write": "auth !=null",  // 2021-1-28
  }
}

Of course my previous fetch logic dose not work, but I do not know how to tell firebase, that user is authorized. This is my service function:

constructor(
  private db: AngularFireDatabase,
  private authService: AuthService,
  public afAuth: AngularFireAuth) { 
  }

  getItems(){
    this.pacRef = this.db.list('pacients');
    this.pacientsData = this.pacRef.snapshotChanges().pipe(
      map(changes=> changes.map(a=>({
        key : a.payload.key, ...a.payload.val() 
        }))));  
    return this.pacientsData;
  }

And here I component where I am trying get data from firabase using gatItems(key) function.

  constructor(private router:Router, 
    private pacientService: PacientServiceService,
    private authService: AuthService) { 
  }

  ngOnInit(): void {

  this.userSub = this.authService.user.subscribe(user=>{
    this.isAuthenticated = !!user;
    this.userToken = user.token;
    console.log(this.isAuthenticated);
    if (this.isAuthenticated) {
      this.pacientService.getItems().subscribe(pacientsData=>{
        this.pacientsData = pacientsData;      
      });
    }
  });
  }

Picture from console: enter image description here Picture from authorization enter image description here

Authorization works and I am getting back token. Any help can help:) This only second month when I building something with Angular.

Given your security rules, you should only call getItems once the user is authenticated.

So:

  ngOnInit(): void {
    this.userSub = this.authService.user.subscribe(user=>{
      this.isAuthenticated = !!user;
      this.userToken = user.token;
      console.log(this.isAuthenticated);
      if (this.isAuthenticated) {
        this.pacientService.getItems(this.userToken).subscribe(pacientsData=>{
          this.pacientsData = pacientsData;      
        });
      }
    });
  }

I also think you don't need to pass the auth key yourself, as the Firebase SDKs handle that behind the scenes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM